HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Starting a fire and forget async method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
startingmethodasyncfireforgetand

Problem

Sonar/FxCop are telling us that we shouldn't use void async methods. That's ok.
This is the current implementation:

private async void InitMethod(ServiceControl serviceControl)
{
    if (serviceControl != null)
    {
        await Task.Factory.StartNew(() => serviceControl.Execute());
    }
}

// fire and forget ... calling from a non-async method!
InitMethod(serviceControl);


Is this a good way or how would you refactor this method?

private async Task InitMethod(ServiceControl serviceControl)
{
    if (serviceControl != null)
    {
        await Task.Factory.StartNew(() => serviceControl.Execute());
    }
}

// fire and forget ... calling from a non-async method!
// when calling without Start then VS is complaining about "not awaiting" this method
InitMethod(serviceControl).Start();

Solution

Just fire the task without async/await.

private void InitMethod(ServiceControl serviceControl)
{
    if (serviceControl != null)
    {
        Task.Factory.StartNew(() => serviceControl.Execute());
    }
}


In a proper F&F task all exception handling (including a final catch, logging, notifications) is done by the task itself, so you don't need exception handling that async/await provides.

Make the method name reflect what it does. I wouldn't mind a name like FireAndForgetXyz

Code Snippets

private void InitMethod(ServiceControl serviceControl)
{
    if (serviceControl != null)
    {
        Task.Factory.StartNew(() => serviceControl.Execute());
    }
}

Context

StackExchange Code Review Q#118030, answer score: 22

Revisions (0)

No revisions yet.