private void ThreadProc(CancellationTokenSource cts) { try { while (!cts.IsCancellationRequested) { if (TcpHelpers.IsMessageAvailable(_client, OnException)) { TcpHelpers.ReadMessageAsync(_stream, _receiveBufferSize, (bytes, exception) => { if (exception != null) { OnException?.Invoke(exception); } if (bytes != null) { _messages.Enqueue(bytes); } }, cts).Wait(); } System.Threading.Thread.Sleep(1); //play nice with other threads } cts.Dispose(); } catch (Exception e) { Log.e("MessageReader Exception: {0}", e.Message); } _thread = null; }
/// <summary> /// Stops waiting for messages /// </summary> public void Stop() { _messageHandlerThread?.Cancel(); _messageHandlerThread = null; _thread?.Cancel(); _thread = null; }
/// <summary> /// Starts waiting for messages /// </summary> public void Start() { Stop(); _messageHandlerThread = new W.Threading.Thread(MessageReceivedHandlerProc); _thread = W.Threading.Thread.Create(ThreadProc); }