Which way is preferred when doing asynchronous WCF calls?
- by Mikael Svenson
When invoking a WCF service asynchronous there seems to be two ways it can be done.
1.
public void One()
{
WcfClient client = new WcfClient();
client.BegindoSearch("input", ResultOne, null);
}
private void ResultOne(IAsyncResult ar)
{
WcfClient client = new WcfClient();
string data = client.EnddoSearch(ar);
}
2.
public void Two()
{
WcfClient client = new WcfClient();
client.doSearchCompleted += TwoCompleted;
client.doSearchAsync("input");
}
void TwoCompleted(object sender, doSearchCompletedEventArgs e)
{
string data = e.Result;
}
And with the new Task<T> class we have an easy third way by wrapping the synchronous operation in a task.
3.
public void Three()
{
WcfClient client = new WcfClient();
var task = Task<string>.Factory.StartNew(() => client.doSearch("input"));
string data = task.Result;
}
They all give you the ability to execute other code while you wait for the result, but I think Task<T> gives better control on what you execute before or after the result is retrieved.
Are there any advantages or disadvantages to using one over the other? Or scenarios where one way of doing it is more preferable?