Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 571
Goran Avatar asked Jan 13 '15 08:01

Goran


People also ask

Can I pass this as parameter?

"Can I pass “this” as a parameter to another function in javascript" --- yes you can, it is an ordinary variable with a reference to current object.

What is the parameters of task?

When you prepare the script to perform the task action, you can specify and set the variable in the script. You can then define the variable as a task parameter with metadata. Ensure that you use the same variable name that was used in the script as the name of the task parameter.

What does Task run do C#?

The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method. It creates a task with the following default values: Its cancellation token is CancellationToken.

How do I create a new task in C#?

To start a task in C#, follow any of the below given ways. Use a delegate to start a task. Task t = new Task(delegate { PrintMessage(); }); t. Start();


1 Answers

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.

like image 141
i3arnon Avatar answered Oct 09 '22 19:10

i3arnon