I'm trying to wrap the SerialPort's read method in a task that can be awaited, that way I can get the benefits of using a CancellationToken and the timeout from the SerialPort object. My issue is that I cannot seem to get the Task to throw a CancellationException. Here's my code...
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);
}
}
Is it because the Port.Read method is a blocking call? Any suggestions?