Code Mahek
  • Blog
  • About
  • Contact
  • Random Clicks
  • Resume
  • Ava Chat Bot

Fragrance
​of Programming

Async/Await, Tasks & IDisposable

9/29/2017

Comments

 
​Couple of times I have encountered the interaction between Task and IDisposable and sometimes it has left me with some serious code bug.
Let’s come to sample code which will explain the crux of the issue. Suppose you have below line of code

Now HttpClient does provides the async version of "GetString" which is "GetStringAsync", so we can write the above line of code as shown below:

Now the above code might look perfect and it may work fine sometime. But it has a serious code bug. In the second version, here's what happens:
  1. A disposable HttpClient object is created
  2. A Task is started to download some text
  3. The client is disposed
  4. The in-progress Task is returned to the caller.
Now if you see, task which is still attached to client but we have closed and cleaned up that object. Now if the task still needs the HttpClient to complete (hint: it does) then it's going to get an ObjectDisposedException.
Now below is the revised version which will run effectively


Now, if you see we have included the "async" and also the corresponding "await" keyword. And it runs effectively like this:
  1. A disposable HttpClient object is created
  2. A Task is started to download some text
  3. The compiler-generated coroutine yields execution until the Task completes
  4. The Task completes
  5. The coroutine continues execution
  6. The client is disposed
  7. The completed task is returned to the caller.
 ​So be very careful when using IDisposable with Task or Async function returning task.
Comments
comments powered by Disqus

    RSS Feed

    Categories

    All
    Azure
    C#
    Cloud
    CodeProject
    CSharp
    DotNet Core
    Jetbrains
    .NET
    Rider
    Source Generators
    SQL
    Tech News
    Ubuntu
    Visual Studio 2015
    Visual Studio 2019
    Windows
    Windows 10

    Archives

    May 2020
    February 2019
    January 2019
    December 2018
    May 2018
    December 2017
    November 2017
    October 2017
    September 2017
    July 2017
    May 2017
    April 2017
    May 2015
    April 2015
    March 2015

    View my profile on LinkedIn

Location

Contact Us

    Subscribe Today!

Submit
  • Blog
  • About
  • Contact
  • Random Clicks
  • Resume
  • Ava Chat Bot