public async Task TestAsync(IPhysicalPort physicalPort) { ITopPort port = new TopPort(physicalPort, new HeadLengthParser(new byte[] { 0x7B }, new GetDataLengthEventHandler(async data => new GetDataLengthRsp() { ErrorCode = Parser.ErrorCode.Success, Length = 48 }))); await port.OpenAsync(); _tcs = new TaskCompletionSource <byte[]>(TaskCreationOptions.RunContinuationsAsynchronously); port.OnReceiveParsedData += async data => { _tcs.TrySetResult(data); _tcs = new TaskCompletionSource <byte[]>(TaskCreationOptions.RunContinuationsAsynchronously); }; CancellationTokenSource cts = new CancellationTokenSource(); _ = Task.Run(async() => { await Task.Delay(3 * 60 * 1000); cts.Cancel(); }); while (!cts.IsCancellationRequested) { var data = await _tcs.Task; Assert.AreEqual(_data.Length, data.Length); for (int i = 0; i < data.Length; i++) { Assert.AreEqual(data[i], _data[i]); } } }
private static async Task SendDataAsync(IPhysicalPort port, string msg, CancellationToken cancellationToken) { var task = Task.Run(async() => { await port.SendDataAsync(Encoding.ASCII.GetBytes("Hello"), cts.Token); await Task.Delay(100); }); }