Skip to content

Latest commit

 

History

History
29 lines (20 loc) · 1.22 KB

GCop655.md

File metadata and controls

29 lines (20 loc) · 1.22 KB

GCop 655

"Change this method to return a Task"

Rule description

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task<T> method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started.

Async methods returning void don’t provide an easy way to notify the calling code that they’ve completed. It’s easy to start async void methods, but it’s not easy to determine when they’ve finished.

It’s clear that async void methods have several disadvantages compared to async Task methods, but they’re inevitable in a particular case: asynchronous event handlers. Further reading.

Example

public async void RunSequence()
{
    SequenceTask = await Task.Factory.StartNew(async () => { await doSequence(); });
}

should be 🡻

public async Task RunSequence()
{
    SequenceTask = await Task.Factory.StartNew(async () => { await doSequence(); });
}