maandag 15 april 2024

Always try/catch in a Task.Run in websockets

When you run the following code:

System.Threading.Tasks.Task.Run(() => { throw new Exception(); });
Console.ReadKey();

You will see that the exception is not shown on screen. That's because the task stops within it's own context.
That behaviour is very problematic if the task contains code that sends information over a websocket. The method that contains the Task.Run will probably still be alive, however the task is stopped. The websocket methods will continue, the task will however not send or receive information anymore. In that case you have a websocket which is alive on a network level but dead on a functional level.
To prevent this situation, always use try/catch blocks within the Task.Run.

Geen opmerkingen:

Een reactie posten