Why wait until the task returned by the async method is blocked?

I am working on a Nancy / ASP.Net project. I tried using WebRequest to retrieve data from another web service, and I executed the request in an async function. I find the problem that when I try to wait for a task returned from a function, it blocks indefinitely. Simplified code looks like this.

using System.Net;
using System.Threading.Tasks;
using Nancy;

public class TestModule : NancyModule{
    public TestModule() {
        Get["/"] = p => "Hello, world";
        Get["/async/"] = p => {
            var req = WebRequest.CreateHttp("http://localhost:13254/");

//          var responseTask = req.GetResponseAsync();  // this works!
            var responseTask = getResponse(req);   // this gets blocked!
            var waitSuccess = responseTask.Wait(10000);

            return waitSuccess ? "Yeah!" : "woooh!";
        };
    }
    async Task<HttpWebResponse> getResponse(HttpWebRequest request) {
        return (HttpWebResponse) await request.GetResponseAsync();
    }
}

The code uses NancyFx, but it also happens on the ASP.Net page on the page. The service on localhost: 13254 is working fine. If I use the task directly returned from the GetResponseAsync () request, the code works fine, but if I wrap it in an asynchronous method, it just blocks.

- , ?:( , async ... , ..

+2
2

MSDN .

, ConfigureAwait(false) , . , await Wait Result, ( , async, .. Get["/async/"] = async p => { ... };).

+3

, Stephen, . :

using System;
using System.Threading;

namespace Utility.Async{
    static public class TPContext{
        static public T Call<T>(Func<T> handler) {
            var currentContext = SynchronizationContext.Current;
            SynchronizationContext.SetSynchronizationContext(null);
            try {
                return handler();
            }finally {
                SynchronizationContext.SetSynchronizationContext(currentContext);
            }
        } 
    }
}

        Get["/async/"] = p => TPContext.Call(() => {
            var req = WebRequest.CreateHttp("http://localhost:13254/");

            var responseTask = getResponse(req);
            var waitSuccess = responseTask.Wait(10000);

            return waitSuccess ? "Yeah!" : "woooh!";
        });

^^ a , ASP.Net.. , Nancy'd , Nancy - Asp.net .

+1

All Articles