我有一个表单,它是在系统托盘中运行的它自己的 UI 线程上创建的,我需要使用来自服务器的 signalR 连接进行操作,我认为该连接在后台线程上运行。我知道在不从 UI 线程访问控件时需要调用控件。我可以使用在表单加载时调用的以下代码进行操作(在我的情况下制作弹出窗口),但由于我对异步相当陌生,因此需要进行完整性检查:
private void WireUpTransport()
{
// connect up to the signalR server
var connection = new HubConnection("http://localhost:32957/");
var messageHub = connection.CreateProxy("message");
var uiThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var backgroundTask = connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection: {0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("The connection was opened successfully");
}
});
// subscribe to the servers Broadcast method
messageHub.On<Domain.Message>("Broadcast", message =>
{
// do our work on the UI thread
var uiTask = backgroundTask.ContinueWith(t =>
{
popupNotifier.TitleText = message.Title + ", Priority: " + message.Priority.ToString();
popupNotifier.ContentText = message.Body;
popupNotifier.Popup();
}, uiThreadScheduler);
});
}
这看起来好吗?它在我的本地机器上运行,但这有可能在我们业务中的每台用户机器上推出,我需要把它做好。