Task run and forget extension

suggest change

In 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.
    });

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents