LocalComputer 上的服务 1 服务启动然后停止 + window 服务中的 SignalR 客户端

The Service 1 service on LocalComputer Started then Stoppped + SignalR Client In window Services

我无法通过异常启动 signalR 客户端 Window 服务。

本地计算机上的服务 1 服务启动然后停止。某些服务如果未被其他服务或程序使用则自动停止

注意:我的服务器在本地主机上运行,​​客户端也在本地主机上运行

我的代码在这里:

IDisposable SignalR { get; set; }
        private System.Diagnostics.EventLog eventLog1;
        private String UserName { get; set; }
        private IHubProxy HubProxy { get; set; }
        const string ServerURI = "http://*:8080/signalr";
        private HubConnection Connection { get; set; }

        public Service1()
        {
            InitializeComponent();
        }

        private async void ConnectAsync()
        {
            try
            {
            Connection = new HubConnection(ServerURI);
            HubProxy = Connection.CreateHubProxy("MyHub");
            //Handle incoming event from server: use Invoke to write to console from SignalR's thread


            HubProxy.On<string, string>("AddMessage", (name, message) =>
            {
                eventLog1.WriteEntry(string.Format("Incoming data: {0} {1}", name, message));
            });
            ServicePointManager.DefaultConnectionLimit = 10;

            eventLog1.WriteEntry("Connected");
            await Connection.Start();
            }
            catch (Exception ex)
            {
                eventLog1.WriteEntry(ex.ToString());
                //No connection: Don't enable Send button or show chat UI
                return;
            }

            //Activate UI
            eventLog1.WriteEntry("Connected to server at " + ServerURI + Environment.NewLine);
        }
        protected override void OnStart(string[] args)
        {
            string abd = "Tariq";

            ConnectAsync();
            HubProxy.Invoke("Send", UserName, abd);
        }

您的 OnStart 代码假定 async void 方法已完成。似乎 HubProxy.Invoke 正在抛出异常,因为它尚未连接。

如果这让您感到困惑,我建议您阅读我的 async intro blog post, and also using my AsyncContextThread type 了解异步 Win32 服务。那么你可以更恰当地避免 async void:

private AsyncContextThread _mainThread = new AsyncContextThread();

protected override void OnStart(string[] args)
{
  _mainThread = new AsyncContextThread();
  _mainThread.Factory.Run(async () =>
  {
    string abd = "Tariq";
    await ConnectAsync();
    HubProxy.Invoke("Send", UserName, abd);
  });
}

private async Task ConnectAsync()
{
  ...
}