When calling the WCF service asynchronously, there are two ways to do this.
one.
WcfClient _client = new WcfClient(); public void One() { _client.BegindoSearch("input", ResultOne, null); } private void ResultOne(IAsyncResult ar) { 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 a simple third way, completing the synchronous operation in the task.
3.
public void Three() { WcfClient client = new WcfClient(); var task = Task<string>.Factory.StartNew(() => client.doSearch("input")); string data = task.Result; }
All of them give you the opportunity to execute different code while you wait for the result, but I think that Task<T> gives better control over what you are doing before or after receiving the result.
Are there any advantages or disadvantages to using one another? Or scenarios where one way to do this is preferable?
Mikael svenson
source share