Xamarin(PCL)-信号R-System.InvalidOperationExceptionConnection在收到调用结果之前已开始重新连接

Xamarin(PCL)-信号R-System.InvalidOperationExceptionConnection在收到调用结果之前已开始重新连接,xamarin,xamarin.ios,xamarin.android,signalr,signalr.client,Xamarin,Xamarin.ios,Xamarin.android,Signalr,Signalr.client,我正在获取System.InvalidOperationExceptionConnection在收到调用结果之前开始重新连接异常有时使用Signal R chat,我正在Xamarin项目的PCL中使用Signal R客户端 这是聊天服务课- public class ChatService : IChatService { private IHubProxy _hubProxy; private HubConnection _hubConnection; private

我正在获取System.InvalidOperationExceptionConnection在收到调用结果之前开始重新连接异常有时使用Signal R chat,我正在Xamarin项目的PCL中使用Signal R客户端

这是聊天服务课-

public class ChatService : IChatService
{
    private IHubProxy _hubProxy;
    private HubConnection _hubConnection;
    private readonly IMobileServiceClient _mobileClient;
    private readonly IInsightsService _insightsService;
    private readonly IChatMessageRepository _chatRepository;

    public ChatService(IMobileServiceClient mobileClient, IInsightsService insightsService, IChatMessageRepository chatRepository)
    {
        _insightsService = insightsService;
        _mobileClient = mobileClient;
        _chatRepository = chatRepository;
    }

    public event EventHandler<ChatMessage> MessageReceived;

    public async Task Connect(bool dismissCurrentConnection = false)
    {
        try
        {
            if (!CrossConnectivity.Current.IsConnected)
            {
                return;
            }

            // Always create a new connection to avoid SignalR close event delays
            if (_hubConnection != null)
            {
                if (!dismissCurrentConnection)
                {
                    return;
                }

                _hubConnection.StateChanged -= OnConnectionStateChangedHandler;
                _hubConnection.Reconnected -= OnReconnectedHandler;
                // DON´T call connection.Dispose() or it may block for 20 seconds
                _hubConnection = null;
                _hubProxy = null;
            }

            _hubConnection = new HubConnection(Identifiers.Environment.ChatUrl);
            // connection.TransportConnectTimeout = TimeSpan.FromSeconds(5);
            _hubConnection.TraceWriter = new DebugTextWriter("SignalR");
            _hubConnection.TraceLevel = TraceLevels.All;
            _hubConnection.StateChanged += OnConnectionStateChangedHandler;
            _hubConnection.Reconnected += OnReconnectedHandler;

            if (_mobileClient.CurrentUser == null)
                throw new Exception("MobileClient.CurrentUser null. You have to login to Azure Mobile Service first.");

            _hubConnection.Headers[HttpHeaders.XZumoAuth] = _mobileClient.CurrentUser.MobileServiceAuthenticationToken;

            _hubProxy = _hubConnection.CreateHubProxy(Identifiers.ChatHubName);

            _hubProxy.On<ChatMessage>("addMessage", message =>
            {
                MessageReceived?.Invoke(this, message);
            });

            if (_hubConnection.State == ConnectionState.Disconnected)
            {
                await _hubConnection.Start();
            }
        }
        catch (Exception ex)
        {
            _insightsService.ReportException(ex);
        }
    }

    private async void OnConnectionStateChangedHandler(StateChange change)
    {
        if (_mobileClient?.CurrentUser != null && change.NewState == ConnectionState.Disconnected && CrossConnectivity.Current.IsConnected)
        {
            // SignalR doesn´t do anything after disconnected state, so we need to manually reconnect
            await Connect(true);
        }
    }

    private void OnReconnectedHandler()
    {
        Debug.WriteLine("[SignalR] SignalR Reconnected to Hub: {0}", Identifiers.ChatHubName);
    }

    public async Task SendMessage(ChatMessage message)
    {
        try
        {               
            if (_hubConnection.State == ConnectionState.Disconnected)
            {
                await Connect(true);
            }

            await _hubProxy.Invoke("Send", message);
        }
        catch (Exception ex)
        {
            try
            {
                await _chatRepository.InsertAsync(message);
            }
            catch (Exception ex2)
            {
                _insightsService.ReportException(ex);
                _insightsService.ReportException(ex2);
                throw ex;
            }
        }
    }

    public async Task JoinChatRoom(string chatRoomId)
    {
        try
        {
            if (_hubConnection.State == ConnectionState.Disconnected)
            {
                await Connect(true);
            }

            await _hubProxy.Invoke("JoinChatRoom", chatRoomId);
        }
        catch (Exception ex)
        {
            _insightsService.ReportException(ex);
        }
    }

    public async Task LeaveChatRoom(string chatRoomId)
    {
        try
        {
            if (_hubConnection.State == ConnectionState.Disconnected)
            {
                await Connect(true);
            }

            await _hubProxy.Invoke("LeaveChatRoom", chatRoomId);
        }
        catch (Exception ex)
        {
            _insightsService.ReportException(ex);
        }
    }

    public void Disconnect()
    {
        try
        {
            if (_hubConnection != null && _hubConnection.State != ConnectionState.Disconnected)
                _hubConnection.Stop();
        }
        catch (Exception ex)
        {
            _insightsService.ReportException(ex);
        }
    }
}
公共类聊天服务:IChatService
{
私有IHubProxy(hubProxy);;
专用HUB连接_HUB连接;
私有只读IMobileServiceClient\u mobileClient;
私人只读IInsightsService_insightsService;
专用只读IChatMessageRepository\u chatRepository;
公共聊天服务(IMobileServiceClient mobileClient、IInsightsService insightsService、IChatMessageRepository聊天库)
{
_insightsService=insightsService;
_移动客户端=移动客户端;
_chatRepository=chatRepository;
}
已接收公共事件事件处理程序消息;
公共异步任务连接(bool dismissCurrentConnection=false)
{
尝试
{
如果(!CrossConnectivity.Current.IsConnected)
{
返回;
}
//始终创建新连接以避免信号关闭事件延迟
如果(_hubConnection!=null)
{
如果(!dismissCurrentConnection)
{
返回;
}
_hubConnection.StateChanged-=OnConnectionStateChangedHandler;
_hubConnection.Reconnected-=OnReconnectedHandler;
//不要调用connection.Dispose(),否则它可能会阻塞20秒
_hubConnection=null;
_hubProxy=null;
}
_hubConnection=新的hubConnection(Identifiers.Environment.ChatUrl);
//connection.TransportConnectTimeout=TimeSpan.FromSeconds(5);
_hubConnection.TraceWriter=新的调试文本编写器(“信号器”);
_hubConnection.TraceLevel=TraceLevel.All;
_hubConnection.StateChanged+=OnConnectionStateChangedHandler;
_hubConnection.Reconnected+=OnReconnectedHandler;
if(_mobileClient.CurrentUser==null)
抛出新异常(“MobileClient.CurrentUser null。您必须先登录Azure移动服务。”);
_hubConnection.Headers[HttpHeaders.XZumoAuth]=\u mobileClient.CurrentUser.MobileServiceAuthenticationToken;
_hubProxy=\u hubConnection.CreateHubProxy(标识符.ChatHubName);
_hubProxy.On(“addMessage”,message=>
{
MessageReceived?调用(此,消息);
});
if(_hubConnection.State==ConnectionState.Disconnected)
{
等待连接。开始();
}
}
捕获(例外情况除外)
{
_insightsService.ReportException(ex);
}
}
私有异步无效OnConnectionStateChangedHandler(StateChange)
{
if(_mobileClient?.CurrentUser!=null&&change.NewState==ConnectionState.Disconnected&&CrossConnectivity.Current.IsConnected)
{
//信号器在断开状态后不做任何事情,所以我们需要手动重新连接
等待连接(true);
}
}
私有void OnReconnectedHandler()
{
Debug.WriteLine(“[SignalR]SignalR重新连接到集线器:{0}”,标识符.ChatHubName);
}
公共异步任务发送消息(ChatMessage)
{
尝试
{               
if(_hubConnection.State==ConnectionState.Disconnected)
{
等待连接(true);
}
wait_hubProxy.Invoke(“发送”,消息);
}
捕获(例外情况除外)
{
尝试
{
wait_chatRepository.InsertAsync(消息);
}
捕获(异常ex2)
{
_insightsService.ReportException(ex);
_insightsService.ReportException(ex2);
掷骰子;
}
}
}
公共异步任务JoinChatRoom(字符串chatRoomId)
{
尝试
{
if(_hubConnection.State==ConnectionState.Disconnected)
{
等待连接(true);
}
wait_hubProxy.Invoke(“JoinChatRoom”,聊天室ID);
}
捕获(例外情况除外)
{
_insightsService.ReportException(ex);
}
}
公共异步任务离开聊天室(字符串聊天室ID)
{
尝试
{
if(_hubConnection.State==ConnectionState.Disconnected)
{
等待连接(true);
}
wait_hubProxy.Invoke(“离开聊天室”,聊天室ID);
}
捕获(例外情况除外)
{
_insightsService.ReportException(ex);
}
}
公共空间断开连接()
{
尝试
{
if(_-hubConnection!=null&&u-hubConnection.State!=ConnectionState.Disconnected)
_hubbonnection.Stop();
}
捕获(例外情况除外)
{
_insightsService.ReportException(ex);
}
}
}
如何防止和捕获此异常?但这并不总是如此