C
C#6mo ago
Asher

Unable to cancel async operation using CancellationToken

Hey all, I have a piece of code which attempts to cancel a UDP Recieve call after 5 seconds
3 Replies
Asher
Asher6mo ago
This is the code particularly:
CancellationTokenSource cts = new CancellationTokenSource();

ValueTask<int> numBytesReceived = sock.ReceiveAsync(res, SocketFlags.None, cts.Token);
cts.CancelAfter(5000);
await numBytesReceived;
Array.Resize(ref res, numBytesReceived.Result);
CancellationTokenSource cts = new CancellationTokenSource();

ValueTask<int> numBytesReceived = sock.ReceiveAsync(res, SocketFlags.None, cts.Token);
cts.CancelAfter(5000);
await numBytesReceived;
Array.Resize(ref res, numBytesReceived.Result);
I am really going crazy trying to cancel this operation if a result is not recieved within 5 seconds, does anyone know why I'm unable to stop this operation?
x0rld
x0rld6mo ago
Stack Overflow
Timeout pattern on task-based asynchronous method in C#
As far as I know, there're two possible patterns to implement a timeout to task-based asynchronous methods: Built-in timeout public Task DoStuffAsync(TimeSpan timeout) This approach is harder to
Asher
Asher6mo ago
@xtreit tried this approach, it seems to still hang for some reason, the RecieveAsync itself just completely (but asynchronously) hangs everything