Do it using assertions and expect keywords to play nicely in C #

I have a situation where I make an async call to the returned method and IDisposable instance. For example:

 HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://www.google.com")); 

Now, before async was on the scene, when working with an IDisposable instance, this call and the code that used the "response" variable would be wrapped in a using statement.

My question is, is this approach correct when the async keyword is selected in the mix? Although the code compiles, will the using statement continue to be executed in both examples below?

Example 1

 using(HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://www.google.com"))) { // Do something with the response return true; } 

Example 2

 using(HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://www.google.com"))) { await this.responseLogger.LogResponseAsync(response); return true; } 
+85
c # asynchronous using-statement
May 15 '13 at 13:36
source share
1 answer

Yes, that should be good.

In the first case, you really say:

  • Asynchronously wait until we can get an answer
  • Use it and dispose of immediately.

In the second case, you say:

  • Asynchronously wait until we can get an answer
  • Wait asynchronously until we complete the answer
  • Eliminate the answer
Operator

A using in the asynchronous method is "odd" in the sense that a Dispose call can be made in another thread with the one that acquired the resource (depending on the context of synchronization, etc.), but this will happen anyway. I suppose that the thing you are waiting for forever shows or fails, of course. (Just as you won't end the Dispose call in non-asynchronous code, if your using statement contains a method call that never returns.)

+86
May 15 '13 at
source share



All Articles