# Starting a fire and forget async method

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();


## 1 Answer

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

• Oh yes ... that is simple. Typically "can't see the forest for the trees" problem. – seveves Jan 27 '16 at 8:34
• @gert-arnold Just be aware of consequences in case of ASP.NET if it is your case. Here is a good article Confusing default scheduler. – Dmitry Nogin Jan 27 '16 at 9:29
• That's a useful addition. A web application should never spawn long-running tasks. (Read, for example, hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx). – Gert Arnold Jan 27 '16 at 9:33
• In this case we don't have an ASP.NET application but a WPF application. – seveves Jan 27 '16 at 11:04
• In that case you may want to ensure that the application can't be closed while a task is still running. – Gert Arnold Jan 27 '16 at 11:38