Why You Should (Almost) Never Write Void Asynchronous Methods
Join the DZone community and get the full member experience.
Join For FreeI will borrow his code to illustrate the point:
async void AcquireFromCamera(object sender, RoutedEventArgs e) { try { var imageStream = await _cameraCapture.Shoot(); var dto = new Dto(){ImageStream = imageStream}; _handler.ImageCaptured(dto); Frame.Navigate(typeof(EditDataPage), dto.Id); } catch (Exception ex) { new MessageDialog(ex.Message).ShowAsync(); } } async void ImageCaptured(Dto dto) { dto.Id = Guid.NewGuid().ToString(); var file = await _fileHndlr.CreateFileAsync(dto.Id); dto.ImageFilePath = file.Path; _fileOperator.StoreStream(dto.ImageStream, file); SaveNewDataItem(dto); var dataItem = dataSource.GetItem(dto.Id); StoreData(dataItem); }
Christiansen argues that this is a buggy piece of software since the AcquireFromCamera
method calls ImageCaptured
as if it was a synchronous method. And he is right since both methods are non-returning. This usage of asynchrony is called fire and forget.
To fix this one needs to change the return type from void
to Task
and the compiler will now warn you with the following warnings:
warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
Void returning asynchronous methods are called fire and forget simply because you don’t need to know when they complete, you initiate them and that is it. The code above requires the ImageCaptured
function to complete before continuing and for that you need to await it.
Change the return type for all asynchronous methods from void
to Task
or Task<T>
. If the asynchronous method does not return any value, use Task
. If it returns an instance of type T, use Task<T>
.
So which methods can be both void
and async
? Only event handlers since the caller does not need to know when the method completes.
Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
How To Integrate Microsoft Team With Cypress Cloud
-
Structured Logging
-
Scaling Site Reliability Engineering (SRE) Teams the Right Way
-
Managing Data Residency, the Demo
Comments