Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

c# - Passing a task as parameter

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
}

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().

What i am currently doing is this:

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

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

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
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...