本地计算机上的服务 1 服务已启动,然后已停止 + 窗口中的 SignalR 客户端
本文关键字:服务 客户端 窗口 SignalR 启动 计算机 然后 | 更新日期: 2023-09-27 18:36:39
>我无法通过异常启动 signalR 客户端窗口服务 .its .
本地计算机上的服务 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
简介博客文章,并将我的AsyncContextThread
类型用于异步 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()
{
...
}