I try to code a simple async write with timeout as below and expect the function to throw a TaskCanceledException given a very large buffer and small waitTime. However, this does not happen. WriteAsync will block for many seconds until the write completes. What am I missing?
public async void WriteWithTimeout(Stream os, byte[] buf, int waitMs)
{
CancellationTokenSource tokenSource = new CancellationTokenSource(waitMs); // cancel after waitMs milliseconds.
await os.WriteAsync(buf, 0, buf.Length, tokenSource.Token);
return;
}
Call from GUI thread:
try
{
WriteWithTimeout(response.OutputStream, buf100M, w1ms);
}
catch(OperationCanceledException e)
{
ConsoleWriteLine("Failed with exception: {0}", e.Message);
}
tokenSource.CancelAfter(TimeSpan.FromMilliseconds(waitMs));
AFTERWriteAsync
and then await it? e.g. this answer here: #23477076 – Hohenlohe