private void Worker(AsyncRWLock commLock, CommHelperBase commHelper, LCGen reqLCG, LCGen ansLCG, int pingInterval, CancellationToken token, Action <Exception> pingThreadFailedCallback) { using (var taskRunner = new AsyncRunner()) { var nullBuff = new byte[0]; while (!token.IsCancellationRequested) { commLock.EnterWriteLock(); try { Answer answer = Answer.Invalid; taskRunner.AddTask(() => commHelper.SendRequest(ReqType.Ping, reqLCG.GenerateValue(), nullBuff, 0, 0)); taskRunner.AddTask(commHelper.ReceiveAnswer, (obj) => answer = obj); taskRunner.RunPendingTasks(); if (answer.ansType != AnsType.Pong || answer.seq != ansLCG.GenerateValue()) { throw new Exception(); } } catch (Exception) { //try to resync try { taskRunner.ExecuteTask(commHelper.Resync); } catch (Exception ex) { pingThreadFailedCallback?.Invoke(ex); return; } } finally { commLock.ExitWriteLock(); } try { taskRunner.ExecuteTask(() => Task.Delay(pingInterval, token)); } catch (TaskCanceledException) { return; } catch (Exception ex) { pingThreadFailedCallback?.Invoke(ex); return; } } } }
public void ReadTimeoutAsync() { const int maxBytesDrop = 100; //drop this max number of bytes to clear port recv-buffer, if any const int timeoutErrorMS = 100; var config = new SerialProtocolConfig(); using (var asyncRunner = new AsyncRunner()) using (var serial = new SerialPort(SerialDeviceManagerTests.portName, config.SERIAL_PORT_SPEED, Parity.None, 8, StopBits.One)) { serial.ReadTimeout = config.CMD_TIMEOUT; serial.WriteTimeout = config.CMD_TIMEOUT; serial.Open(); var bytesLeft = maxBytesDrop; var sw = new Stopwatch(); var tmpBuff = new byte[1]; while (bytesLeft > 0) { bool timedOut = false; //start timer sw.Restart(); //read byte try { bytesLeft -= asyncRunner.ExecuteTask(() => serial.BaseStream.ReadAsync(tmpBuff, 0, 1)); } catch (TimeoutException) { timedOut = true; } //stop timer sw.Stop(); //if timed out - measure interval, exit if (timedOut) { Assert.LessOrEqual(Math.Abs(sw.ElapsedMilliseconds - config.CMD_TIMEOUT), timeoutErrorMS); break; } } if (bytesLeft < 1) { throw new Exception("Failed to establish valid test conditions! Aborting test!"); } } }
public void Connect() { asyncRunner.ExecuteTask(ConnectAsync); }