[英]SignalR doesn't work with .net core WPF application
I'm working on a .net core application that will use SignalR for communication between server and clients.我正在开发一个 .net 核心应用程序,它将使用 SignalR 在服务器和客户端之间进行通信。 It seems that .net core WPF client is not able to start a connection with the server.似乎 .net 核心 WPF 客户端无法启动与服务器的连接。 After reaching StartAsync method it hangs without any information.到达 StartAsync 方法后,它挂起,没有任何信息。 Here is a sample code for that.这是一个示例代码。 I have prepared also a console client which is using the same way for connecting to the server and it is working properly.我还准备了一个控制台客户端,它使用相同的方式连接到服务器并且工作正常。 Could anyone have encountered similar problems?有没有人遇到过类似的问题?
It's dead-locked.它是死锁的。 Do not use .Wait()
in a UI synchronization context.不要在 UI 同步上下文中使用.Wait()
。
Incase of link-rot, here is the code you posted:万一链接腐烂,这是您发布的代码:
namespace Communication
{
public class LiveService
{
private readonly HubConnection _hubConnection;
public LiveService()
{
var hubConnectionBuilder = new HubConnectionBuilder();
_hubConnection = hubConnectionBuilder
.WithUrl("https://localhost:5001/signalrTestHub/")
.Build();
_hubConnection.StartAsync(default).Wait();
}
public async Task Send(CancellationToken cancellationToken = default)
{
await _hubConnection.SendAsync("SendTestMsg", "Test value", cancellationToken);
}
}
}
This is an example on how to fix it:这是有关如何修复它的示例:
namespace Communication
{
public class LiveService
{
private readonly HubConnection _hubConnection;
private readonly Task _initialized;
public LiveService()
{
var hubConnectionBuilder = new HubConnectionBuilder();
_hubConnection = hubConnectionBuilder
.WithUrl("https://localhost:5001/signalrTestHub/")
.Build();
_initialized = _hubConnection.StartAsync(default);
}
public async Task Send(CancellationToken cancellationToken = default)
{
await _initialized;
await _hubConnection.SendAsync("SendTestMsg", "Test value", cancellationToken);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.