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 1
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
-
\$\begingroup\$ Oh yes ... that is simple. Typically "can't see the forest for the trees" problem. \$\endgroup\$seveves– seveves2016年01月27日 08:34:41 +00:00Commented 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\$Dmitry Nogin– Dmitry Nogin2016年01月27日 09:29:30 +00:00Commented 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\$Gert Arnold– Gert Arnold2016年01月27日 09:33:23 +00:00Commented Jan 27, 2016 at 9:33
-
\$\begingroup\$ In this case we don't have an ASP.NET application but a WPF application. \$\endgroup\$seveves– seveves2016年01月27日 11:04:51 +00:00Commented 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\$Gert Arnold– Gert Arnold2016年01月27日 11:38:02 +00:00Commented Jan 27, 2016 at 11:38
Explore related questions
See similar questions with these tags.