将函数包装为异步任务 [英] Wrap a function as an async task

查看:110
本文介绍了将函数包装为异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要包装的函数,以便可以使用async/await模式:

I have a function that I would like to wrap so that I can use the async/await pattern:

wcfClientService.GetSomeString(parameter);

这是来自WCF客户端的呼叫,我正在尝试使其异步,但这并不重要(我知道WCF支持异步,但是假设我们无权访问WCF代码).

It's a call from a WCF client that I'm trying to make asynchronous, but that's not important (I know WCF supports async, but let's assume we don't have access to the WCF code).

我正在尝试用Task<T>.Factory.FromAsync方法包装该方法,但似乎无法正确地做到这一点:

I'm trying to wrap the method with the Task<T>.Factory.FromAsync method, but can't seem to get it right:

private Task<string> WrapWcfServiceAsyncTask(uint parameter)
{
    Func<uint, string> func = i => { return wcfClientService.GetSomeString(parameter); };

    var t = Task<string>.Factory.FromAsync(
                                           // What goes here?
                                          );
    return t;
}

甚至更好的是,有人可以编写一个将方法作为参数并包装并返回Task<T>的方法吗?

Or even better, can someone write a method that takes a method as a parameter, and wraps and returns a Task<T> for it?

推荐答案

您要尝试做的是

What you're trying to do is async over sync. You have a synchronous operation and you want to pretend it's asynchronous .

您可以使用Task.Run做到这一点:

You can do that with Task.Run:

var result = await Task.Run(() => wcfClientService.GetSomeString(parameter));

但这没什么意义,因为您只是将工作从一个ThreadPool线程转移到另一个.

but it's pointless as you're just offloading work from one ThreadPool thread to another.

如果您想要异步操作,则需要以某种方式(例如async-await或Begin/End等)开始进行异步操作.

If you want an asynchronous operation it needs to be asynchronous to begin with in some way, either with async-await or Begin/End, etc.

如果您有已经异步的BeginGetSomeString/EndSomeString,则可以使用FromAsync将其转换为异步等待.

If you had BeginGetSomeString/EndSomeString which is already asynchronous you could have used FromAsync to turn it into async-await.

这篇关于将函数包装为异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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