Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pause and continue a TPL task?

I have scenario where I have a couple of background tasks (TPL tasks) which run on their own individual schedules. Task 1 is deemed to have a higher priority than Task 2.

If the scheduler wants to run Task 1, I need to check if Task 2 is running and pause it while Task 1 completes execution.

Is this even possible? If yes, how can I achieve this?

like image 358
Ravi Y Avatar asked May 15 '26 22:05

Ravi Y


2 Answers

You can use signaling constructs to achieve this.

static ManualResetEvent mre = new ManualResetEvent(false);

var Task1=Task.Factory.StartNew(() =>
{
    Console.WriteLine("Executing Task 1");
    Thread.Sleep(2000); //A Long running operation
    Console.WriteLine("Task 1 Completed");
    mre.Set(); //signal the task completion to task 2.
});


var Task2=Task.Factory.StartNew(() =>
{
    if (!Task1.IsCompleted) //check if task1 is completed.
    {
        mre.WaitOne(); //wait until Task 1 Completes
        Console.WriteLine("Executing Task 2");
        Thread.Sleep(2000);
        Console.WriteLine("Task 2 Completed");    
        doSomeTask();
    }
     else
    {
        //Task 1 is already completed
        doSomeTask();
    }

});
like image 123
Prabhu Murthy Avatar answered May 17 '26 10:05

Prabhu Murthy


The easy, non-blocking way is Task.Delay:

http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.delay(v=vs.110).aspx

// Some code here

await Task.Delay(2000); // Pause for 2 seconds, without blocking

// Code to execute after waiting
like image 20
Chris Moschini Avatar answered May 17 '26 12:05

Chris Moschini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!