Task run and forget extension

suggest change

In certain cases (e.g. logging) it might be useful to run task and do not await for the result. The following extension allows to run task and continue execution of the rest 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:


Async/Await, BackgroundWorker, Task and Thread examples:
* Task
* Thread
* Task run and forget extension

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
110 Async/Await, BackgroundWorker, Task and Thread examples
127 Caching
135 Pointers
147 C# Script