Which method is preferred when making asynchronous WCF calls?

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?

+7
c # asynchronous wcf
source share
2 answers

I would not use the final version, because it will start the operation in the workflow instead of the input / output stream. This is especially bad if you do this inside ASP.NET, where workflows are needed to serve requests. Not to mention the fact that you are still blocking the main thread, waiting for the task to finish when you check its Result , so technically you spend two workflows or one work and user interface.

The BeginXYZ and XyzAsync for WCF clients work differently - you have to choose the appropriate version based on the option you want to support (APC or event-driven, respectively). For example, a BeginXYZ version would be (possibly counterintuitively) easier to use on an ASP.NET (or MVC) asynchronous page, while a version of XyzAsync would be easier to use in Windows form.

+5
source share

The problem is with your first example. You should not create a new instance of WcfClient when calling EndDoSearch. You must either save the original instance in the field, or pass it as a status parameter.

But overall, I prefer option # 1, because it greatly simplifies the use of an anonymous method to process the result.

 var client = new WcfClient(); client.BeginDoSearch("input", ar => { var result = client.EndDoSearch(ar); // blah blah }, null); 
+2
source share

All Articles