Do using statements and await keywords play nicely in c#

前端 未结 1 1775
失恋的感觉
失恋的感觉 2020-11-29 23:17

I have a situation where I am making an async call to a method that returns and IDisposable instance. For example:

HttpResponseMess         


        
相关标签:
1条回答
  • 2020-11-30 00:11

    Yes, that should be fine.

    In the first case, you're really saying:

    • Asynchronously wait until we can get the response
    • Use it and dispose of it immediately

    In the second case, you're saying:

    • Asynchronously wait until we can get the response
    • Asynchronously wait until we've logged the response
    • Dispose of the response

    A using statement in an async method is "odd" in that the Dispose call may execute in a different thread to the one which acquired the resource (depending on synchronization context etc) but it will still happen... assuming the thing you're waiting for ever shows up or fail, of course. (Just like you won't end up calling Dispose in non-async code if your using statement contains a call to a method which never returns.)

    0 讨论(0)
提交回复
热议问题