【发布时间】:2018-05-23 04:07:49
【问题描述】:
我正在尝试将 SerialPort 的读取方法包装在一个可以等待的任务中,这样我就可以获得使用 CancellationToken 和 SerialPort 对象超时的好处。我的问题是我似乎无法让任务抛出 CancellationException。这是我的代码...
static CancellationTokenSource Source = new CancellationTokenSource();
static void Main(string[] args)
{
TestAsyncWrapperToken();
Console.WriteLine("Press any key to cancel");
Console.ReadKey(true);
Source.Cancel();
Console.WriteLine("Source.Cancel called");
Console.ReadLine();
}
static async void TestAsyncWrapperToken()
{
try
{
using (var Port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One))
{
Port.Open();
var Buffer = new byte[1];
await Task.Factory.StartNew(() =>
{
Console.WriteLine("Starting Read");
Port.ReadTimeout = 5000;
Port.Read(Buffer, 0, Buffer.Length);
}, Source.Token);
}
}
catch (TaskCanceledException)
{
Console.WriteLine("Task Cancelled");
}
catch (TimeoutException)
{
Console.WriteLine("Timeout on Port");
}
catch (Exception Exc)
{
Console.WriteLine("Exception encountered {0}", Exc);
}
}
是因为 Port.Read 方法是阻塞调用吗?有什么建议?
【问题讨论】:
标签: c# asynchronous serial-port task cancellation