首页 > 解决方案 > 当客户端空闲时,signalR 冻结 UI

问题描述

我遇到了主应用程序窗口冻结的问题。我开始与 signalR 服务器通信,然后当我最小化主窗口并且暂时不打开它时,它挂起。

    public static NotificationServerProxy GetNotificationServerProxy(string notificationServerURI, User user, Dispatcher dispatcher = null)
    {
        NotificationServerProxy nsp = new NotificationServerProxy
        {
            dispatcher = dispatcher ?? System.Windows.Application.Current.Dispatcher
        };
        User = user;
        canRegisterClientMethods = nsp.Connect2(notificationServerURI, hubName).Result;
        return nsp;
    }

该问题也可以通过 TeamViewer 连接到工作站来重现。我需要做的就是启动主应用程序窗口,断开与 TeamViewer 的连接,几秒钟后重新连接,然后主窗口挂起

    public async Task<bool> Connect2(string notificationServerURI, string hubName)
    {
        {
            WriteExceptionToLog($"{logPrefix}, notificationServer.IsNotConnected");
            try
            {
                
                WriteExceptionToLog($"{logPrefix}, BEFORE CreateConnected() serverURI = {notificationServerURI}, hubName = {hubName}");
                
                hubConnection = new HubConnection(notificationServerURI);
                hubConnection.Credentials = CredentialCache.DefaultNetworkCredentials;
                hubConnection.StateChanged += OnConnectionStateChanged;
                hubProxy = hubConnection.CreateHubProxy(hubName);

                WriteExceptionToLog($"{logPrefix}, AFTER CreateConnected()");
                
                await StartConnectionAsync();
                
                return true;
            }
            catch (Exception ex)
            {
                WriteExceptionToLog($"{logPrefix}, ERROR IN StartConnection(): {ex.Message}");
            }
        }

        WriteExceptionToLog($"{logPrefix}, NotificationServerConnect() END");
        return false;
    }

    private async Task StartConnectionAsync()
    {
        await hubConnection.Start();
    }

标签: c#winformsasync-awaitsignalr

解决方案


推荐阅读