0

我有一个表单,它是在系统托盘中运行的它自己的 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);
        });
    }

这看起来好吗?它在我的本地机器上运行,但这有可能在我们业务中的每台用户机器上推出,我需要把它做好。

4

1 回答 1

4

从技术上讲,您应该在收听之前连接所有通知(使用On<T>) 。Start至于您的异步工作,我不太确定您要做什么,但由于某种原因,您将通知链接到您的 UIOn<T>backgroundTask变量中,该变量是调用返回给您的任务Start。没有理由参与其中。

所以这可能是你想要的:

private void WireUpTransport()
{
    // connect up to the signalR server
    var connection = new HubConnection("http://localhost:32957/");
    var messageHub = connection.CreateProxy("message");
    var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();

    // subscribe to the servers Broadcast method
    messageHub.On<Domain.Message>("Broadcast", message =>
    {
        // do our work on the UI thread
        Task.Factory.StartNew(
            () =>
            {
                popupNotifier.TitleText = message.Title + ", Priority: " + message.Priority.ToString();
                popupNotifier.ContentText = message.Body;
                popupNotifier.Popup();
            }, 
            CancellationToken.None,
            TaskCreationOptions.None,
            uiTaskScheduler);
    });

    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");
        }
    });
}
于 2012-11-13T17:25:31.140 回答