PremKumar Shanmugam
PremKumar Shanmugam

Reputation: 441

Execute a Method after completion of any one task in c#

i have two tasks running asynchronously.

var task1=Task.Run(async()=>{method1();});
var task2=Task.Run(async()=>{method1();});

If any one of the task completed,i want to run an another method(eg:method2()).And after completion of second task, i want to run the same method again(i.e.,method2()) .How to do this?

Upvotes: 0

Views: 4252

Answers (3)

John Wu
John Wu

Reputation: 52290

If any one of the task completed,i want to run an another method(eg:method2()).And after completion of second task, i want to run the same method again(i.e.,method2())

Sounds like you have two parallel paths of execution, each composed of two method calls in series. So....

var task1 = Task.Run( async () => { await method1(); await method2(); });  
var task2 = Task.Run( async () => { await method1(); await method2(); });  

await Task.WhenAll( new Task[] { task1, task2 } );

Upvotes: 1

Link
Link

Reputation: 1711

If I understand you correctly you have a bunch of tasks and if one of them is finshed you want to run another task?

You can use Task.WhenAny(). It accepts an array of tasks and you can await until the first one is finished

var tasks = new[] { Method1(), Method2(), Method3() };
await Task.WhenAny(tasks);
await Method4();

MSDN: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenany?view=netcore-3.1

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81573

Assuming your methods are awaitable, Maybe you want something like this

await Task.WhenAny(method1,method1); // wait for something to finish
await method2(); // await for method 2
await Task.WhenAll(method1,method1); // run it all again

// or endlessly
while(!theEndofTheUniverse)
{
   await Task.WhenAny(method1,method1);
   await method2();
} // rinse and repeate 

Upvotes: 2

Related Questions