ShirazITCo
ShirazITCo

Reputation: 1041

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;
}

Upvotes: 0

Views: 424

Answers (2)

svick
svick

Reputation: 244757

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.

Upvotes: 2

Paul Michalik
Paul Michalik

Reputation: 4381

Try this, data correctness checks etc. omitted but you ignored them either :-):

public async Task<string> UploadRequestAsync(string url, string postdata) 
{  
    string result = await Encoding.GetString(
        new WebClient().UploadData(new Uri(uri), "POST", Encoding.UTF8.GetBytes(postdata)));
    return result; 
} 

You somehow doing the work twice, awaiting a explicitly started task. I'd be curious to see what the generated code for this looks like... And of course, in production code use the proper classes from .NET 4.5.

Upvotes: 0

Related Questions