Over a million developers have joined DZone.

Why You Should (Almost) Never Write Void Asynchronous Methods

·
I came across this interesting post by Christian Jacobsen titled async/await in C# – a disaster waiting to happen? in which he says that simple refactoring can introduce serious bugs in async code. While there is definitely something to be said about possible problems with the new Async feature, his example can teach us something.

I 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.

Topics:

Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}