DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Why You Should (Almost) Never Write Void Asynchronous Methods

Toni Petrina user avatar by
Toni Petrina
·
Oct. 12, 12 · Interview
Like (0)
Save
Tweet
Share
4.83K Views

Join the DZone community and get the full member experience.

Join For Free
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.

POST (HTTP) Software Event

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Stream Processing vs. Batch Processing: What to Know
  • Quick Pattern-Matching Queries in PostgreSQL and YugabyteDB
  • Bye-Bye, Regular Dev [Comic]
  • 5 Factors When Selecting a Database

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: