Async HTTP Post data in a single function using Async CTP
I am trying to use Async CTP to create a single function that starts async and returns a value.
here is my sample code. I don't know why it doesn't populate the "resp" variable when it returns.
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;
}
I also tried this, but the program was freezing (don't just do anything for a while). perhaps 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);
}
+3
source to share
2 answers
You can use an extension method UploadDataTaskAsync
(part of the CTP) instead and don't have to write this 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;
}
Implementing this extension method correctly handles event subscriptions and ensures that the task is completed when the event does fire.
+7
source to share