25

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
 }
Selim Balci
  • 940
  • 2
  • 11
  • 26

1 Answers1

25

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 suggests the discard because SomeSideTaskToBeForgotten(); returns something i.e. not void, but adding the discard also suppresses the warning, because it informs the compiler that an await hasn't been omitted accidentally.

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
  • I think there is a miscomprehension here. Await doesn't get skipped once the task is over; it hands over control to the calling function until the awaited task returns, until which execution continues statements after the await. – Denis G. Labrecque Feb 07 '22 at 17:06
  • @Denis What `await`? There is no `await` in the OP's code. – Johnathan Barclay Feb 07 '22 at 20:01