I was pretty excited about the async CTP announcement. I was eager to use async in my projects and wanted to get rid off most of the delegates which make all the more unreadable and maintenance nightmare for a new resource. We as developers always want to see the code in debug mode and check the flow of the code. With the async implementation, the code looks more cleaner.
So long story short, i wanted to use async CTP in my silverlight project. So i took the reference of AsyncCtpLibrary_Silverlight and i assume that now all my WCF proxy client will have the [Methodname]TaskAsync method where i can use await keyword. To my surprise, it was not there. I thought i might need to “Update Service Reference” so that the code can regenerated and i will get access to TaskAsync methods. But it didn’t work either. Then i started doing some research and i realized that Async CTP does not support generated WCF proxy class, that was pretty disappointing hmm….
Since i wanted to use async anyways, i wrote an extension method. This probably is not the best way but it worked for me. I was able to use await keyword at the method call and go rid off the delegates.
Here’s the example of the extension method i wrote:
public static Task<List<Customers>> GetCustomerInformationTaskAsync(this IService webClient, int aCustomerID)
{
var TaskCompSource = new TaskCompletionSource<List<Customers>>();
webClient.BeginGetCustomerInformation(aCustomerID, o =>
{
try
{
TaskCompSource.TrySetResult(webClient.BeginGetCustomerInformation(o));
}
catch (Exception e)
{
TaskCompSource.TrySetException(e);
}
}
, null);
return TaskCompSource.Task;
This extension method is ready to use in your client.
List<Customers> CustomerList = await objService.GetCustomerInformationTaskAsync(_customerId);
Happy coding!!!
No comments:
Post a Comment