Task.Run swallows the exceptions [Answered]
Pretty self explanatory. The minimal reproducible example throws an exception in the
Task.Run(...)
and it doesn't rethrow it out of the Task.Run(...)
scope.
12 Replies
uh yeah, that code is a little sus
you're firing and forgetting the task. You need to await it for the exception to be thrown
yeah, but isn't there another way?
since in my real use case I cannot remove the Task.Run
No. The exception is happening outside the call stack
what are you trying to do at a high level? I know Polly can be used for retrying operations and such
this is my real use case scenario
it shouldn't block
the SendAsync is currently one statement but it should be a Task.Run loop too
I was thinking of
and wrapping the StartAsync logic in a Task.Run(...);
here we go, wew. Those Task.Runs should instead be Polly policies or whatever they're called. You need to break it down into what specifically needs to be retried.
oh I see you're using Task.Run because you want it to run stuff in the background?
ye
put your polly retries inside of those tasks around whatever operation you need retried
the body of the while loop maybe
yeah, but I need to recreate the whole ClientWebSocket instance at each reconnect
wouldn't that retry the loop only?
ClientWebSocket has to be reinstantiated once it throws, stops or whatever
yeah. You'll essentially need a Task.Run for a watchdog. I guess it'll await those worker tasks
(also I recommend passing around cancellation tokens, otherwise you can't stop the execution)
true, I didn't implement those yet
https://github.com/teamhitori/mulplay-container-web/blob/eb39e75e74c44d3c290bcc30737f8b861031fb37/dotnet/Components/WebSocketService.cs
quick search on github gave me this result
someone did quite the same
✅ This post has been marked as answered!