将任务作为参数传递 [英] Passing a task as parameter

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

问题描述

我不确定这是否可行,所以在这里:

I am not sure whether this is possible, so here me out:

我有一系列执行多项操作的动作

I have a sequence of action to perform multiple

async Task MethodA(...)
{
    // some code
    // a call to specific Async IO bound method
    // some code
}

也有 MethodB() MethodC()等,所有代码都具有完全相同的代码,但对特定异步IO绑定的调用除外方法。我试图找到一种将任务指针传递给方法的方法,以便我们稍后可以在Method()中执行它。

there are also MethodB(), MethodC(), etc, and all of the have exactly the same code, except for the call to specific Async IO bound method. I am trying to find a way to pass a task pointer to a method, so that we can execute it later in a Method().

我目前正在做的是

private async Task Method(Func<Task<Entity>> func)
{
    // some code
    var a = await task.Run(func);
    // some code
}

var task = async () => await CallToIOBoundTask(params);
Method(task);

但是,此代码每次都会拉出一个新线程,这对于IO绑定任务不是必需的,并且应该避免。

This code, however, pulls a new thread each time, which is not required for IO bound task, and should be avoided.

因此,有没有一种方法可以重构代码,以便不使用ThreadPool线程?一个目标是拥有这样的代码:

So, is there a way to refactor the code so that no ThreadPool thread is used? A goal is to have a code like this:

private async Task Method(Task<Entity> task)
{
    // some code
    var a = await task;
    // some code
}

同样重要的是要提到不同IO调用具有不同的方法签名。另外,任务只能在 Method()主体中开始执行,而不能在之前执行。

It is also important to mention that different IO calls have different method signatures. Also, a task can start to execute only in Method() body, and not before.

推荐答案

当然,只需调用 func ,取回任务,然后 await 即可:

Of course, simply invoke the func, get back a task, and await it:

async Task Method(Func<Task<Entity>> func)
{
    // some code
    var a = await func();
    // some code
}

此外,当您发送该代码时lambda表达式,因为它所做的只是调用 async 方法,该方法本身会返回任务,因此它不必是 async 本身:

Also, when you're sending that lambda expression, since all it's doing is calling an async method which in itself returns a task, it doesn't need to be async in itself:

Method(() => CallToIOBoundTask(params));

这很好,只要所有这些调用都返回 Task< Entity> 。否则,您只能使用 Task (这意味着开始操作并等待其完成),并且您将无法使用结果。

That's fine as long as all these calls return Task<Entity>. If not, you can only use Task (which means starting the operation and awaiting its completion) and you won't be able to use the result.

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

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