C
C#•12mo 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
AsherOP•12mo 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 👻 🎃
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
AsherOP•12mo ago
@xtreit tried this approach, it seems to still hang for some reason, the RecieveAsync itself just completely (but asynchronously) hangs everything
Want results from more Discord servers?
Add your server