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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With