哪种方式是preferred做异步调用WCF的时候? [英] Which way is preferred when doing asynchronous WCF calls?

查看:139
本文介绍了哪种方式是preferred做异步调用WCF的时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当调用WCF服务异步似乎有两个方面是可以做到的。

When invoking a WCF service asynchronous there seems to be two ways it can be done.

1

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;
}

和新任务< T> 类,所以必须通过包装同步操作任务中的简单的第三条道路。

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;
}

他们全都给你,而你的结果,等待执行其他code的能力,但我认为任务&LT; T&GT; 给你执行什么更好的控制之前或结果被检索后

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.

有什么优点或缺点,使用了另一种?或者场景,这样做的一个方法是比较preferable?

Are there any advantages or disadvantages to using one over the other? Or scenarios where one way of doing it is more preferable?

推荐答案

我会的不可以使用最终版本,因为它会在一个工作线程,而不是一个I / O线程运行操作。这是特别不好的,如果你正在做内部的ASP.NET,在需要的工作线程来服务请求。更何况,你还是阻塞主线程等待任务时,你检查它的结果完成,所以在技术上你浪费的两个工作线程,或者一个工人和用户界面。

I would not use the final version because it will run the operation on a worker thread instead of an I/O thread. This is especially bad if you're doing it inside ASP.NET, where the worker threads are needed to serve requests. Not to mention, you're still blocking on the main thread waiting for the task to finish when you check its Result, so technically you're wasting two worker threads, or one worker and the UI.

BeginXYZ XyzAsync 的WCF客户端的方法基本相同的方式工作 - 你应该选择基于相应的版本对使用情况下,你要支持(无论是APC或事件驱动,分别)。例如, BeginXyz 版本会(或许与直觉不符)更容易在ASP.NET(或MVC)异步页面中使用,而 XyzAsync 版本会更容易在Windows窗体中使用。

The BeginXYZ and XyzAsync methods for WCF clients work essentially the same way - you should choose the appropriate version based on the use case you want to support (either APC or event-driven, respectively). For example, the BeginXyz version would (perhaps counterintuitively) be easier to use within an ASP.NET (or MVC) async page, whereas the XyzAsync version would be easier to use in a Windows Form.

这篇关于哪种方式是preferred做异步调用WCF的时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆