Passing a task as a parameter

I'm not sure if this is possible, so here:

I have a sequence of actions to perform several

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

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

I am currently doing the following:

 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, draws a new thread each time, which is not required for the IO-related task, and should be avoided.

So, is there a way to reorganize the code so that ThreadPool is not used? The goal is to have code like this:

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

It is also important to note that different I / O calls have different method signatures. In addition, a task can only be launched in the Method() tag, and not earlier.

+7
c # task-parallel-library async-await
source share
1 answer

Of course, just call func , return the task and await it:

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

Also, when you submit this lambda expression, since all it does is call the async method, which itself returns the task, it should not be async on its own:

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

This is fine as long as all these calls return to Task<Entity> . If not, you can use Task (which means starting the operation and completing it), and you will not be able to use the result.

+16
source share

All Articles