Async call with await in HttpClient never returns

后端 未结 3 551
栀梦
栀梦 2020-11-29 19:33

I have a call I am making from inside a xaml-based, C# metro application on the Win8 CP; this call simply hits a web service and returns JSON data.



        
3条回答
  •  借酒劲吻你
    2020-11-29 20:26

    Disclaimer: I don't like the ConfigureAwait() solution because I find it non-intuitive and hard to remember. Instead I came to the conclusion to wrap non awaited method calls in Task.Run(() => myAsyncMethodNotUsingAwait()). This seems to work 100% but might just be a race condition!? I'm not so sure what is going on to be honest. This conclusion might be wrong and I risk my StackOverflow points here to hopefully learn from the comments :-P. Please do read them!

    I just had the problem as described and found more info here.

    The statement is: "you can't call an asynchronous method"

    await asyncmethod2()
    

    from a method that blocks

    myAsyncMethod().Result
    

    In my case I couldn't change the calling method and it wasn't async. But I didn't actually care about the result. As I remember it also didn't work removing the .Result and have the await missing.

    So I did this:

    public void Configure()
    {
        var data = "my data";
        Task.Run(() => NotifyApi(data));
    }
    
    private async Task NotifyApi(bool data)
    {
        var toSend = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
        await client.PostAsync("http://...", data);
    }
    

    In my case I didn't care about the result in the calling non-async method but I guess that is quite common in this use case. You can use the result in the calling async method.

提交回复
热议问题