-1

I have the following code:

    public MainWindow()
    {
        InitializeComponent();
        RunAsync().Wait();
    }

    private static async Task RunAsync()
    {
        var baseAddress = new Uri("https://api.trakt.tv/");
        using (var httpClient = new HttpClient { BaseAddress = baseAddress })
        {
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("trakt-api-version", "2");

            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("trakt-api-key", "");

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            using (var response = await httpClient.GetAsync("search?query=Arrow&type=Show"))
            {
                string responseData = await response.Content.ReadAsStringAsync();
            }
        }
    }

When I run it, it get stuck at the part:

using (var response = await httpClient.GetAsync("search?query=Arrow&type=Show"))

This never finishes running. But if I take off the .Wait() from RunAsync().Wait(); then the code run to the end normally. Why is it getting stuck when I put .Wait() on the method call?

I have to put it, because if i don't the rest of the code will continue to run and wont wait the method to complete...

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
Gabriel Duarte
  • 974
  • 1
  • 13
  • 28
  • look at the comments on this answer: http://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously/11782373#11782373 – AK_ Feb 01 '15 at 21:43
  • I have a blog post on [`async` constructors](http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html) that you may find useful. – Stephen Cleary Feb 02 '15 at 12:53

1 Answers1

4

You've got a deadlock here.

Code after await will be executed in the same thread as it started. This is the way await works. But since you've already blocked the thread by calling Wait(), it goes to be locked forever

Alex K.
  • 784
  • 5
  • 12
  • So does it means that even if i don't put Wait() after RunAsync() the code will wait the method end before it continues? – Gabriel Duarte Feb 01 '15 at 21:37
  • Nope. In your case it just finishes MainWindow constructor. And when httpClient.GetAsync() method is executed, you'll get code in RunAsync() continued. – Alex K. Feb 01 '15 at 21:41
  • but how can i make MainWindow constructor just continue when RunAsync() finishes? – Gabriel Duarte Feb 01 '15 at 21:56
  • I think you shouldnt go with smth async when you need sync behavior. You could either use WebClient that provides sync methods or rewrite your RunAsync() in syncronous manner. E.g. instead of await httpClient.GetAsync("search?query=Arrow&type=Show") you'll use httpClient.GetAsync("search?query=Arrow&type=Show").Result etc. – Alex K. Feb 01 '15 at 22:01
  • 1
    @GabrielDuarte: You should move that out of the constructor, into and `await`able `async` method. – SLaks Feb 01 '15 at 23:00