Search code examples
c#asynchronousasync-ctp

Async CTP method freeze when return value


Im trying to make an async method that returns a value. everything work when use the method without return. you can process data , but the problem appears when the return clause added. the program freeze completely without any error or for a while.

please see the code:

public void runTheAsync(){
   string resp = sendRequest("http://google.com","x=y").Result;
}

public async Task<string> sendRequest(string url, string postdata)
{
    //There is no problem if you use void as the return value , the problem appears when Task<string> used. the program fully go to freeze.
    Console.WriteLine("On the UI thread.");

    string result = await TaskEx.Run(() =>
    {
        Console.WriteLine("Starting CPU-intensive work on background thread...");
        string work = webRequest(url,postdata);
        return work;
    });

    return result;
}

public string webRequest(string url, string postdata)
{
    string _return = "";
    WebClient client = new WebClient();
    byte[] data = Encoding.UTF8.GetBytes(postdata);
    Uri uri = new Uri(url);
    _return = System.Text.Encoding.UTF8.GetString(client.UploadData(uri, "POST", data));
    return _return;
}

Solution

  • string resp = sendRequest("http://google.com","x=y").Result;
    

    That's your problem. If you call Result on a Task, it blocks until the Task finishes.

    Instead, you can do this:

    public async void runTheAsync()
    {
       string resp = await sendRequest("http://google.com","x=y");
    }
    

    But creating async void methods should be avoided. Whether you actually can avoid it, depends on how are you calling it.