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?
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();
}
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With