Task run and forget extension
suggest changeIn certain cases (e.g. logging) it might be useful to run a task and not await the result. The following extension allows you to run a task and continue execution of the rest of the code:
public static class TaskExtensions
{
public static async void RunAndForget(
this Task task, Action<Exception> onException = null)
{
try
{
await task;
}
catch (Exception ex)
{
onException?.Invoke(ex);
}
}
}
The result is awaited only inside the extension method. Since async/await is used, it is possible to catch an exception and call an optional method for handling it.
An example how to use the extension:
var task = Task.FromResult(0); // Or any other task from e.g. external lib.
task.RunAndForget(
e =>
{
// Something went wrong, handle it.
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents