Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async HTTP Post data in single function using Async CTP

I'm trying use Async CTP to build single function that run async and return a value.

here is my sample code. i don't know why it dont fill the "resp" variable at return.

public async Task<string> sendRequest(string url, string postdata)
{
    WebClient client = new WebClient();
    byte[] data = Encoding.UTF8.GetBytes(postdata);
    Uri uri = new Uri(url);
    client.UploadDataAsync(uri,"POST", data);
    string resp = "";
    await TaskEx.Run(()=>
    client.UploadDataCompleted += (e, s) =>
    {
        resp = System.Text.Encoding.UTF8.GetString(s.Result);
    });
    return resp;
}

Also I tried this but the program freeze ( do nothing more not just for a while ). maybe any correction can help.

public async Task<string> sendRequest(string url, string postdata)
{
    string resp = "";
    WebClient client = new WebClient();
    byte[] data = Encoding.UTF8.GetBytes(postdata);
    Uri uri = new Uri(url);
    data = await TaskEx.Run(()=>client.UploadData(uri,"POST", data));

    return System.Text.Encoding.UTF8.GetString(data);
}
like image 833
ShirazITCo Avatar asked May 20 '26 10:05

ShirazITCo


1 Answers

You could, instead, use the UploadDataTaskAsync extension method (part of the CTP), and not have to write that plumbing code yourself:

public async Task<string> sendRequest(string url, string postdata)
{
    WebClient client = new WebClient();
    byte[] data = Encoding.UTF8.GetBytes(postdata);
    Uri uri = new Uri(url);
    resp = System.Text.Encoding.UTF8.GetString(await client.UploadDataTaskAsync(uri,"POST", data));
    return resp;
}

The implementation of that extension method handles the event subscription correctly, and ensures that the task is completed when the event actually fires.

like image 66
Damien_The_Unbeliever Avatar answered May 23 '26 00:05

Damien_The_Unbeliever