How can I pause and continue a TPL task?

c#, multithreading, task-parallel-library

Solution

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

});

Problem

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?

Original source