how to wait for webclient OpenReadAsync to complete - c#

I am using WebClient to download some stuff from internet in Windows Phone 8.1 app.
Below is the sample code i am using in my app - where i am calling below method, but my webclient is not waiting to complete the read operation and returning immediately after OpenReadAsync call.
how can i make sure that my method return operation must wait till OpenReadCompleted event is completed?
I have seen multiple similar questions, but couldn't find a solution.
MyCustomObject externalObj; // my custom object
private static void CheckNetworkFile()
{
try
{
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += (s, e) =>
{
externalObj = myReadWebclientResponse(e.Result); // my custom method to read the response
};
webClient.OpenReadAsync(new Uri("http://externalURl.com/sample.xml", UriKind.Absolute));
}
catch (Exception)
{
externalObj = null;
}
}

I would advise you to use WebClient.OpenReadTaskAsync with a combination of the async/await keywords introduced in .NET 4.5 instead. You need to add the async keyword to your method, make it return a Task and it is advisable to end your method with the Async postfix:
MyCustomObject externalObj;
private static async Task CheckNetworkFileAsync()
{
try
{
WebClient webClient = new WebClient();
Stream stream = await webClient.OpenReadTaskAsync(new Uri("http://externalURl.com/sample.xml", UriKind.Absolute));
externalObj = myReadWebclientResponse(stream);
}
catch (Exception)
{
externalObj = null;
}
}
Edit:
As you said, WebClient.OpenReadTaskAsync isn't available for WP8.1, So lets create an Extension Method so it will be:
public static class WebClientExtensions
{
public static Task<Stream> OpenReadTaskAsync(this WebClient client, Uri uri)
{
var tcs = new TaskCompletionSource<Stream>();
OpenReadCompletedEventHandler openReadEventHandler = null;
openReadEventHandler = (sender, args) =>
{
try
{
tcs.SetResult(args.Result);
}
catch (Exception e)
{
tcs.SetException(e);
}
};
client.OpenReadCompleted += openReadEventHandler;
client.OpenReadAsync(uri);
return tcs.Task;
}
}
Now you can use it on your WebClient.
You can find great reading material in the async-await wiki and by simply filtering by that tag in the search bar.

I hope this is not too off topic, but others who are researching this might like to know that the above code sample can also be used for WCF calls in Silverlight. Be sure to add the Microsoft.Bcl.Async NuGet package first. Here is a WCF code example:
public static async Task<string> AuthenticateAsync(string userName, string password)
{
var dataAccessServiceClient = new DataAccessServiceClient("DataAccessService");
var taskCompletionSource = new TaskCompletionSource<string>();
EventHandler<AuthenticateCompletedEventArgs> completedHandler = null;
completedHandler = (s, args) =>
{
try
{
taskCompletionSource.SetResult(args.Result);
}
catch (Exception e)
{
taskCompletionSource.SetException(e);
}
};
dataAccessServiceClient.AuthenticateCompleted += completedHandler;
dataAccessServiceClient.AuthenticateAsync(userName, password);
return await taskCompletionSource.Task;
}
It can be called like this:
var result = await AuthenticateAsync(username, password);

Related

c# wrapping a Task into a another Task

I am trying to use inter process communication to send from one instance of my program its content to the other instance. The code I have under here is working but it makes the first instance freeze and only continues running when the second instansce is created and the data is passed back.I suspect its because messaging_server0() is not a async task. How would one approach this problem. Is there a way to make messaging_server0 async? or am I missing something?
main loop contains this piece of code
var makeTask = Task<string>.Factory.StartNew(() => pipe_server.messaging_server0());
if (makeTask.Result != null) {
dataGrid_logic.DataGridLoadTarget(makeTask.Result);
}
and on the other side I have messaging_server0
public static string messaging_server0()
{
using (var messagebus1 = new TinyMessageBus("ExampleChannel"))
{
string ret = null;
messagebus1.MessageReceived += (sender, e) => ret = Encoding.UTF8.GetString(e.Message);
while (true)
{
if (ret != null)
{
return ret;
}
}
}
}
The method names are going to be refactored.
I would suggest following approach:
public static async Task<string> messaging_server0()
{
using (var messagebus1 = new TinyMessageBus("ExampleChannel"))
{
var taskCompletition = new TaskCompletionSource<string>();
messagebus1.MessageReceived +=
(sender, e) =>
{
var ret = Encoding.UTF8.GetString(e.Message);
taskCompletition.TrySetResult(ret);
};
return await taskCompletition.Task;
}
}
Obviously you would need to add some error handling, time outs if needed etc.
with the help of alek kowalczyk and some digging I came up with this code
private async void xxx()
{
var makeTask = Task<string>.Factory.StartNew(() => pipe_server.messaging_server());
await pipe_server.messaging_server();
{
dataGrid_logic.DataGridLoadTarget(makeTask.Result);
}
}
plus the snippet he posted.
This works perfectly. thanks

My desktop application hangs on web API service call with async and await

I am getting lots of delay when saving data in database. I have one exe (Deskptop Application) which reads data from serial port and push that entry in to database through web API service but my application get hangs on this line:
httpClient.PostAsync("api/MyController/Save", httpConent).Result;
This exe is responsible to call my web API service method and save data to my database.
This is my code:
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int dataLength = _serialPort.BytesToRead;
byte[] data = new byte[dataLength];
int nbrDataRead = _serialPort.Read(data, 0, dataLength);
if (nbrDataRead == 0)
return;
// Send data to whom ever interested
if (NewSerialDataRecieved != null)
{
NewSerialDataRecieved(this, new SerialDataEventArgs(data));
}
}
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e)
{
if (this.InvokeRequired)
{
// Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway.
//// Fired-off asynchronously; let the current thread continue.
this.BeginInvoke(new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e });
return;
}
//data is converted to text
string str = Encoding.ASCII.GetString(e.Data);
if (!string.IsNullOrEmpty(str))
{
CallWebservice(str)
}
}
public void CallWebservice(string xmlRequest)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("WebService Url");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StringContent httpConent = new StringContent(xmlRequest, Encoding.UTF8);
HttpResponseMessage responseMessage = null;
try
{
responseMessage = httpClient.PostAsync("api/MyController/Save", httpConent).Result;
}
catch (Exception ex)
{
if (responseMessage == null)
{
responseMessage = new HttpResponseMessage();
}
responseMessage.StatusCode = HttpStatusCode.InternalServerError;
responseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
}
}
}
My web api method:
public async Task<HttpResponseMessage> Save(HttpRequestMessage request)
{
var requestdata = request.Content.ReadAsStringAsync().Result;//extract Users Id's from this
var users=context.User.Where(t => (t.Stats == userId1) || (t.Stats == userId2)).ToList();
var objUsersMapping= new UsersMapping();
objUsersMapping.Work1 = users[0].Work1;
objUsersMapping.Work2 = users[1].Work1;
await this.SaveUsersMapping(objUsersMapping);
}
public async Task<UsersMapping> SaveUsersMapping(UsersMapping objUsersMapping)
{
using (var context = new MyEntities())
{
try
{
context.UsersMapping.Add(objUsersMapping);
await context.SaveChangesAsync();
return objUsersMapping;
}
catch (Exception foExe)
{
return null;
}
}
}
I haven't work much on Windows application so I am not understanding why my application is hanging.
Note: data will be continuously coming to my serial port so saving data through web service should not disturb _serialPort_DataReceived event.
This is a summary of my comments beneath the OP's question
You are calling an asynchronous method synchronously. That will cause the current thread to block. Get rid of the .Result and alter the rest of the code accordingly (like including async and await there too).
e.g. change this line
responseMessage = httpClient.PostAsync("api/MyController/Save", httpConent).Result;
...to:
responseMessage = await httpClient.PostAsync("api/MyController/Save", httpConent);
Your method signature will need to be changed as follows:
public async Task CallWebservice(string xmlRequest)
{
}
Any method that calls it will also need to be async and use await for example your _spManager_NewSerialDataRecieved() method.
Note it has been changed from void to async void. Note too the await prior to CallWebservice().
async void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e)
{
if (this.InvokeRequired)
{
// Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway.
//// Fired-off asynchronously; let the current thread continue.
this.BeginInvoke(new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e });
return;
}
//data is converted to text
string str = Encoding.ASCII.GetString(e.Data);
if (!string.IsNullOrEmpty(str))
{
await CallWebservice(str)
}
}
A note on async void
Because the above method is an event handler it is fine for the method to be async void. Generally you want to avoid async void in non event handler code. For more info see this brilliant article by Mr Stephen Cleary.
Is this the only problem sir??
You should fix your async Save() method on the server too as it also has a .Result(). That will block the current thread on the server. Prefix it with a await. Generally you want to avoid .Result as a means to wait for the task to complete. It is safe to use as a means to obtain the result after you have awaited it, but there are more elegant ways to await and get the result in a single line of code. e.g. x = await FooAsync();.

Make TaskCompletionSource<T>.Task run in background from asp.net mvc request

In one action of my MVC 4 apps, I have a call:
public ActionResult Test()
{
DownloadAsync("uri","file path");
return Content("OK");
}
DownloadAsync return a Task and I expect to see the DownloadAsync run in background. But I always see that MVC only response when the Task of DownloadAsync is completed (means that need wait for download complete before response). If I wrap the async call in to Task.Run() or Task.Factory.StartNew(), then it works as my expectation. Here's method DownloadAsync:
private Task DownloadAsync(string url, string originalFile)
{
var tsc = new TaskCompletionSource<bool>();
var client = new WebClient();
AsyncCompletedEventHandler completedHandler = null;
completedHandler = (s, e) =>
{
var wc = (WebClient)s;
wc.DownloadFileCompleted -= completedHandler;
if (e.Cancelled)
{
tsc.TrySetCanceled();
}
else if (e.Error != null)
{
tsc.TrySetException(e.Error);
}
else
{
tsc.SetResult(true);
}
wc.Dispose();
};
client.DownloadFileCompleted += completedHandler;
client.DownloadFileAsync(new Uri(url), originalFile);
return tsc.Task;
}
So my question are:
Why MVC request need wait for complete Task in this case? Is there any special for Task created by TaskCompletionSource<T>?
How to make the Task of DownloadAsync run in background without pause the response of MVC request?
Thanks,

What to use if i want to return the result of a webclient

take the following code:
public async Task<string> AuthenticatedGetData(string url, string token)
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(WebClient_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(url + "?oauth_token=" + token));
}
private void WebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string response = e.Result;
}
WebClient_DownloadStringCompleted gets called... and response = the response I want... Great. perfect...
Now consider how i'm calling this AuthenticatedGetData method:
It is being called from a kind of repository... The repository wants a string so that it can serialize and do stuff with the resulting object...
So everything is running async fromt he repository... The call gets made to the authenticatedgetdata, it then makes a request... but because the downloadstringasync does not have a .Result() method and because downloadstringcompleted requires a void method to call... I cannot return the result string to the calling repository.
Any ideas on what I must do to get client.DownloadStringAsync to return the response string on completion?
Is it that I just simply have to tightly couple my data access operations to this specific app.. It seems so un..re-usable :( I really want to keep my whole authentication stuff totally separate from what's going to happen. and I do not want to keep repeating the above code for each repository, because it's going to be the same for each anyway!
Edit:://
I've created an abstract method in my class that deals with the above requests... and then I extend this class with my repository and implement the abstract method. sound good?
Edit:// Calling code as requested:
public class OrganisationRepository
{
PostRequest postRequest;
public OrganisationRepository()
{
this.postRequest = new PostRequest();
}
public IEnumerable<Organisation> GetAll()
{
string requestUrl = BlaBla.APIURL + "/org/";
string response = postRequest.AuthenticatedGetData(requestUrl, BlaBla.Contract.AccessToken).Result;
}
}
public class PostRequest
{
public Task<string> AuthenticatedGetData(string url, string token)
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
WebClient client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
if (e.Error != null)
{
tcs.TrySetException(e.Error);
}
else if (e.Cancelled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(e.Result);
}
};
client.DownloadStringAsync(new Uri(url + "?oauth_token=" + token));
return tcs.Task;
}
}
I'm not sure what the windows-phone-8 limitations are with regards to this. But I think this should work.
public Task<string> AuthenticatedGetData(string url, string token)
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
WebClient client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
if (e.Error != null)
{
tcs.TrySetException(e.Error);
}
else if (e.Cancelled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(e.Result);
}
};
client.DownloadStringAsync(new Uri(url + "?oauth_token=" + token));
return tcs.Task;
}
You might also be able to get away with this (not sure if it works on windows phone 8)
public Task<string> AuthenticatedGetData(string url, string token)
{
WebClient client = new WebClient();
return client.DownloadStringTaskAsync(new Uri(url + "?oauth_token=" + token));
}
A solution is to not use the WebClient library at all. Here's the issue: you are awaiting your async AuthenticatedGetData Task, but it does nothing because the Task has no await calls in it meaning it will finish instantly. Calling the .result on the task will always be null because you can never return a value in that method. The WebClient relies on calling a function call after the DownloadCompleted event is fired. However, there is no way for anyone to know exactly when this happens, unless they also subscribe to that DownloadCompleted event handler, which is silly. I recommend making a true async web request service using HttpWebRequest http://blogs.msdn.com/b/andy_wigley/archive/2013/02/07/async-and-await-for-http-networking-on-windows-phone.aspx good luck.

Populate and return entities from DownloadStringCompleted handler in Windows Phone app

I am having a method which fetches HTML from a url, extracts entities by parsing it, and returns List of entites. Here is sample code:
public List<Entity> FetchEntities()
{
List<Entity> myList = new List<Entity>();
string url = "<myUrl>";
string response = String.Empty;
client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
response = e.Result;
// parse response
// extract content and generate entities
// <---- I am currently filling list here
};
client.DownloadStringAsync(new Uri(url));
return myList;
}
The problem is while async call is in progress control returns with empty myList. How can I prevent this. My ultimate goal is to return filled list.
And also this method is in a seperate class library project and being called from windows phone application and I have to keep it like that only. Is there any way to do this or I am missing something? Any help will be greatly appreciated.
You can either pass callback to the method like this and make it async without Tasks, so u have to update method usage slightly.
public void FetchEntities(
Action<List<Entity>> resultCallback,
Action<string> errorCallback)
{
List<Entity> myList = new List<Entity>();
string url = "<myUrl>";
string response = String.Empty;
client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
response = e.Result;
// parse response
// extract content and generate entities
// <---- I am currently filling list here
if (response == null)
{
if (errorCallback != null)
errorCallback("Ooops, something bad happened");
}
else
{
if (callback != null)
callback(myList);
}
};
client.DownloadStringAsync(new Uri(url));
}
The other option is to force it be synchronous. Like that
public List<Entity> FetchEntities()
{
List<Entity> myList = new List<Entity>();
string url = "<myUrl>";
string response = String.Empty;
client = new WebClient();
AutoResetEvent waitHandle = new AutoResetEvent(false);
client.DownloadStringCompleted += (sender, e) =>
{
response = e.Result;
// parse response
// extract content and generate entities
// <---- I am currently filling list here
waitHandle.Set();
};
client.DownloadStringAsync(new Uri(url));
waitHandle.WaitOne();
return myList;
}
That is the point of asynchronous programming to be non-blocking. You can pass a callback as a parameter and handle the result somewhere else instead of trying to return it.
If you need to return the result you can use this TPL library, I've been using it without problem for a while now.
public Task<string> GetWebResultAsync(string url)
{
var tcs = new TaskCompletionSource<string>();
var client = new WebClient();
DownloadStringCompletedEventHandler h = null;
h = (sender, args) =>
{
if (args.Cancelled)
{
tcs.SetCanceled();
}
else if (args.Error != null)
{
tcs.SetException(args.Error);
}
else
{
tcs.SetResult(args.Result);
}
client.DownloadStringCompleted -= h;
};
client.DownloadStringCompleted += h;
client.DownloadStringAsync(new Uri(url));
return tcs.Task;
}
}
And calling it is exactly how you use TPL in .net 4.0
GetWebResultAsnyc(url).ContinueWith((t) =>
{
t.Result //this is the downloaded string
});
or:
var downloadTask = GetWebResultAsync(url);
downloadTask.Wait();
var result = downloadTask.Result; //this is the downloaded string
Hope this helps :)

Categories