Повторное подключение Signal R, похоже, создает новый поток - PullRequest
1 голос
/ 29 мая 2020

У нас есть концентратор siglnalR, размещенный в IIS, и приложение ядра WPF. net, которое подключается. При первом запуске все работает отлично. Однако, когда IIS перерабатывает пул приложений, клиент WPF успешно повторно подключается, но (как кажется) в другом потоке, когда пользователь пытается выполнить действие (открыть новое окно WPF) - возникает следующая ошибка при создании нового экземпляра открываемого окна: -

"The calling thread must be STA, because many UI components require this"

Вот как мы подключаемся к хабу: -

 private async void Connect()
    {
        try
        {
            _signalRConnection.On<Notification>(NotificationMessageStr, (message) =>
            {
                if (message != null && _signalRConnection != null)
                {
                    OnProcessMessage(message);
                }
            }
            );


            _signalRConnection.Reconnecting += error =>
            {
                OnReconnecting("Connection lost - Attempting to reconnect.");
                return Task.CompletedTask;
            };

            _signalRConnection.Reconnected += connectionId =>
            {
                OnReconnected("Reconnected");

                return Task.CompletedTask;
            };

            _signalRConnection.Closed += error =>
            {
                OnLostConnection("Failed to connect");
                // Notify users the connection has been closed or manually try to restart the connection.

                return Task.CompletedTask;
            };
            try
        {
            //Connect to the server
            await _signalRConnection.StartAsync();


        }
        catch (Exception ex)
        {


        }

        }
        catch (Exception ex)
        {

        }
    }

Когда сообщение получено от хаба, мы вызов: -

 private void SubscriveToNewNotification()
        {
            vm.NewNotification += (sender, e) => { 
ShowNotificationAlert(e.NotificationMessage); };
        }


    private void ShowNotificationAlert(Notification notification) {
        NotificationAlert notificationAlert = new NotificationAlert();
        notificationAlert.notification = notification;
        notificationAlert.Show();
    }

А вот это: -

NotificationAlert notificationAlert = new NotificationAlert();

Это не удается.

Так устанавливается соединение: -

private void InitializeViewModel()
    {

        try
        {
string serviceAddress = "xxxx/notificationHub";


            connectHub = NotificationHubManager.CreateNotificationHub(serviceAddress, userInfo);
        }
        catch (System.Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message + "--");
        }


        connectHub.ProcessMessage += (sender, e) =>
        {
         // THIS IS WHERE IT FALLS OVER
            NotificationAlert n = new NotificationAlert();
            OnNotificationReceived(e.NotificationMessage);
        };

- Это центр уведомлений

 public static NotificationHubConnect CreateNotificationHub(string address, ISwiftUser userInfo = null)
    {
        HubConnection hubConnection = new HubConnectionBuilder()
           .WithUrl(address)
           .WithAutomaticReconnect()
           .Build();
        try
        {
            var result = new NotificationHubConnect(hubConnection, userInfo);
            return result;
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

Есть ли способ запустить повторное подключение в том же потоке?

...