Which way is preferred when doing asynchronous WCF calls?

Posted by Mikael Svenson on Stack Overflow See other posts from Stack Overflow or by Mikael Svenson
Published on 2010-04-10T20:20:08Z Indexed on 2010/04/10 20:23 UTC
Read the original article Hit count: 166

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#