使用异步任务调用同步WCF服务 [英] Using asynchronous tasks to call synchronous WCF service

查看:29
本文介绍了使用异步任务调用同步WCF服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WCF 服务,由服务客户端调用.我想使用 async/await 构造来包装对此的调用;但是,服务和服务客户​​端是.NET3.5.我对此的解决方案如下:

I have a WCF service, called by a service client. I'd like to use the async / await constructs to wrap the call to this; however, the service and service client are .NET3.5. My solution to this is as follows:

private async Task<ObservableCollection<MyEntity>> LoadData(ParamData param)
{
        ServiceClient svc = new ServiceClient();
        int results = 0;

        // Set-up parameters
        myParams = BuildParams(param);

        // Call a count function to see how much data we're talking about
        // This call should be relatively quick
        var counter = Task.Factory.StartNew(() =>
        {
            results = svc.GetResultCount(myParams);
        }).ContinueWith((task) =>
        {
            if (results <= 10000 ||
                (MessageBox.Show("More than 10000 results, still retrieve data?"), MessageBoxButton.YesNo) == MessageBoxResult .Yes))
            {
                return svc.Search(myParams);
            }
        });
}

我收到编译错误:

Since 'System.Action<System.Threading.Tasks.Task>' returns void, a return keyword must not be followed by an object expression

所以,我的问题是,是否可以以这种方式运行同步方法,如果可以,我做错了什么?我的目标是可以像这样调用该方法:

So, my question is, is it possible to run a synchronous method in this fashion and, if so, what am I doing wrong? My objective is that the method can be called like so:

var data = await LoadData(params);

推荐答案

当您添加服务引用时,有一个选项可以生成操作的异步版本.

When you add the Service Reference there is an option to generate async versions of the operations.

这是(旧的)APM 模式(IAsyncResult、BeginMethod、EndMethod).您可以使用 FromAsync 将此挂接到异步/等待中:

This is the (older) APM pattern (IAsyncResult, BeginMethod, EndMethod). You can hook this into async/wait with FromAsync :

 var task = Task.Factory.FromAsync(BeginGetResultCount, EndGetResultCount, myParams);

当你有很多调用时,这样更好,不会浪费那么多线程来等待 I/O.

When you have many calls this is better, it doesn't waste so many threads to wait for I/O.

这篇关于使用异步任务调用同步WCF服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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