Robo Kiwi

  • Blog
  • Wiki
  • GitHub

Contents

Wiki / .NET / Asynchronous Programming / Gotchas
1 min read

Gotchas

Do’s and don’ts when working with async

Async / Await Gotchas

Spot the bug:

    internal Task<DataFormat> TestAsync()
    {
        using (var stream = File.Open("test.dat", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            return StreamProcessingUtil.DoSomethingAsync(stream);
        }
    }

Oops! We actually need to await the method that gets passed the stream, as without an await, the closing of the using will be hit, disposing the stream before our method has a chance to start or finish what it wants to do.

Solution:

    internal async Task<DataFormat> TestAsync()
    {
        using (var stream = File.Open("test.dat", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            return await StreamProcessingUtil.DoSomethingAsync(stream);
        }
    }
  • .NET
    • Testing
    • .NET Patterns
    • Asynchronous Programming
    • MSBuild
  • Microsoft Dynamics
  • Apps & Tools
  • Data & Databases
    • SQL
  • Debugging
  • JavaScript
  • Microsoft Office
  • Practices
  • Principles & Theory
  • Scripting
    • PowerShell
  • Security
  • Source Control
  • Web Technologies
    • JavaScript
    • React
  • Windows
Copyright © David Moore 2021

Netlify badge Built with Hugo