5

I'm wodering what happens in the scenario where an discarded Task throws?

Example: What happens with exception thrown by SendMailAsync?

Do I need to worry about/handle it? (i.e. security issues, memory leaks or annything else..)

async SendMailAsync(){ ... long process that throws an exception...}

Method(){
//_ = is discard as opposed to await
 _ = SendMailAsync();

}
Tomas Hesse
  • 385
  • 3
  • 10

2 Answers2

4

I'm wo[n]dering what happens in the scenario where [a] discarded Task throws?

The task gets terminated. If you have attached an event handler to TaskScheduler.UnobservedTaskException, your event handler will be called.

Do I need to worry about/handle it? (i.e. security issues, memory leaks or annything else..)

That depends on whether you care about the fact that the Task threw an exception. If you don't, you can just ignore it. If you want to log the fact that mail sending failed (or inform the user of your application), you should not ignore it.

If you don't want to await the Task, you can alternatively use Task.ContinueWith with TaskContinuationOptions.OnlyOnFaulted.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
2

I'm wodering what happens in the scenario where an discarded Task throws?

As noted in the other answer, TaskScheduler.UnobservedTaskException is raised. By default, exceptions from discarded tasks are ignored.

Do I need to worry about/handle it? (i.e. security issues, memory leaks or annything else..)

I strongly recommend against discarding tasks. The main reason behind this recommendation is that the containing application cannot know whether it is safe to shut down. Any ongoing work is terminated when the containing application exits. So if you're fine with SendMailAsync silently doing nothing when the application shuts down, then go ahead and discard. But if you actually want the email to be sent (or a log message on failure), then you should be awaiting the task.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Thank you Stephen! I've read some of your blogs in the past. In this case I'm fine with it doing nothing. I was just worried that I would have some other unexpected side effects – Tomas Hesse Jul 29 '21 at 07:51