Friday, October 31, 2014

FireAndForget a Task with AggressiveInlining

When working with tasks you will get a warning if you do not use a task returned from a method. However, you might actually want to fire and forget that task. So what do you do?

One option is to create an extension method for your task to mark it as fire and forget. Aside from removing the warning, it also gives you the nice ability to find all usages.

When creating this method it is a good idea to mark it with the aggressive inlining attribute. This will cause the compiler to try and inline the method to try and optimize performance.

Implementation and Unit Test

public static class TaskExtensions
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void FireAndForget(this Task task)
    {
        // Do Nothing
    }
}
 
public class TaskExtensionTests
{
    [Fact]
    public void FireAndForget()
    {
        Task
            .Delay(100)
            .ContinueWith(t =>
            {
                // TODO: Stuff!
            })
            .FireAndForget();
    }
}

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics