I have an async method in a WCF service, and a client that consume this method. When I call the method, the GUI of the client is blocked until the async method finish. My code is the following:
SERVICE
public IAsyncResult BeginAsyncMethod(CustomClass paramCustomClass, AsyncCallback callback, object state)
{
Task<bool> task = Task<bool>.Factory.StartNew(p => slowMethod(paramCustomClass, state);
return task.ContinueWith(res => callback(task));
}
public bool EndAsyncMethod(IAsyncResult paramResult)
{
return ((Task<bool>)paramResult).Result;
}
slowMethod is a dummy method with a for from i = 0 to 1000000000.
CLIENT
private void callAsyncMethod()
{
Task<bool> task = Task<bool>.Factory.FromAsync(_proxy.Proxy.BeginAsyncMethod, _proxy.Proxy.EndAsyncMethod, CustomClass, null);
bool hasFinished= task.Result;
}
In the client, I have a button that calls the callAsyncMethod, and when I click the button, the GUI gets bloked while the slowMethod is running.
If I am not wrong, the async methods return the control to the caller to avoid the program was blocked, but in my case this does not occur. have I misunderstood something? I am using in the wrong way the async methods?
Thanks.
Daimroc.
Even though the methods are asynchronous, you’re waiting for the result to return, effectively blocking the calling thread (UI). When you access the
Resultproperty of theTaskobject, if the task hasn’t been completed, it will block until the result is available.You should call the asynchronous method asynchronously. If you’re using .NET 4.5, you can use the await keyword:
Otherwise you’ll really need to make the call asynchronous