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

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

问题描述

我不确定这是否可行,所以我来了:

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()等,除了调用特定的Async 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,就可以了.如果没有,您只能使用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天全站免登陆