7
\$\begingroup\$

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();
\$\endgroup\$

1 Answer 1

22
\$\begingroup\$

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

\$\endgroup\$
8
  • \$\begingroup\$ Oh yes ... that is simple. Typically "can't see the forest for the trees" problem. \$\endgroup\$
    – seveves
    Commented Jan 27, 2016 at 8:34
  • 3
    \$\begingroup\$ @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. \$\endgroup\$ Commented Jan 27, 2016 at 9:29
  • \$\begingroup\$ That's a useful addition. A web application should never spawn long-running tasks. (Read, for example, hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx). \$\endgroup\$ Commented Jan 27, 2016 at 9:33
  • \$\begingroup\$ In this case we don't have an ASP.NET application but a WPF application. \$\endgroup\$
    – seveves
    Commented Jan 27, 2016 at 11:04
  • \$\begingroup\$ In that case you may want to ensure that the application can't be closed while a task is still running. \$\endgroup\$ Commented Jan 27, 2016 at 11:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.