locked
Have an async/await block RRS feed

  • Question

  • I need a way to convert an async method into a standard blocking method. I know this goes against the design, but I have a special need case where I have to be guaranteed that not other code will sneak in and execute on the same thread between the Await and the continuation of an Async method that implements the Async/Await pattern.

    • Moved by John Boylan Monday, January 14, 2013 9:33 PM
    Tuesday, December 25, 2012 1:25 PM

Answers

  • If that method returns a Task, you can simply call Wait() on it. Most asynchronous methods return Tasks, so that should be fine.

    If it's for example WinRT IAsyncInfo, you can first call AsTask() and then Wait() on that.

    Tuesday, January 1, 2013 3:24 PM

All replies

  • It might help if you actually explained what your "special need case" actually is.

    But converting async method into a synchronous one shouldn't be hard in most cases. Use synchronous versions of the asynchronous methods you're using when they exist. When they don't, synchronously wait for them to finish (e.g. by calling Wait() or Result).

    If you're asking how to do it without modifying the code in your method, then that would probably require using a custom TaskScheduler, especially if your method uses ConfigureAwait().

    But you're certainly right that doing this goes against the intention of async-await, and you should avoid doing something like this if possible.

    • Edited by svickMVP Wednesday, December 26, 2012 3:12 PM
    Wednesday, December 26, 2012 3:11 PM
  • The use case is this. I have an async method that I can't change and a sync equivalent version does not exist. I don't own it but I must call it. I also have to guarantee that no other code executes on the calling thread while I am awaiting this method. I need a way to block the tread while awaiting. Since the Async/Await pattern allows other code to execute on the calling thread while awaiting this causes some negative adverse effects. The call is not on the UI thread so it does not matter if it blocks.

    Is there something like:

    Wait MyMethodAsync() 

    instead of 

    Await MyMethodAsync()


    Tuesday, January 1, 2013 12:13 PM
  • If that method returns a Task, you can simply call Wait() on it. Most asynchronous methods return Tasks, so that should be fine.

    If it's for example WinRT IAsyncInfo, you can first call AsTask() and then Wait() on that.

    Tuesday, January 1, 2013 3:24 PM