Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Fire and Forget Task and discard

I need to do a fire and forget call to some async method. I realised VS is suggesting that I can set the call to a _discard and the IDE warning goes away. But I'm not sure if that call is still not awaited when used with the discard. Would it be?

 public async Task<object> SomeSideTaskToBeForgotten()
 {
     ...blah blah
 }

 public async Task MainTask()
 {
     ..some stuff
     _ = SomeSideTaskToBeForgotten(); //is this still fire and forget?
     ..some other stuff
 }
like image 441
Michael Wayne Avatar asked Nov 26 '19 09:11

Michael Wayne


1 Answers

Yes, it's still fire and forget.

When SomeSideTaskToBeForgotten(); returns a Task, the remainder of your method will execute, without waiting for the Task to complete.

The discard just makes explicit the fact that the Task isn't required for any further processing.

VS will be recommending the discard because SomeSideTaskToBeForgotten(); returns something i.e. not void.

like image 199
Johnathan Barclay Avatar answered Sep 20 '22 10:09

Johnathan Barclay