Let's say I have an application that has two tasks running.
TriggerHour1 = new TimeSpan(0, 1, 0);
Task.Run(async () =>
{
while (true)
{
var triggerTime = DateTime.Today + TriggerHour1 - DateTime.Now;
if (triggerTime < TimeSpan.Zero)
triggerTime = triggerTime.Add(new TimeSpan(24, 0, 0));
await Task.Delay(triggerTime);
Console.WriteLine("RunningTask1 finished")
}
});
TriggerHour2 = new TimeSpan(0, 1, 0);
Task.Run(async () =>
{
while (true)
{
var triggerTime = DateTime.Today + TriggerHour2 - DateTime.Now;
if (triggerTime < TimeSpan.Zero)
triggerTime = triggerTime.Add(new TimeSpan(24, 0, 0));
await Task.Delay(triggerTime);
Console.WriteLine("RunningTask2 finished")
}
});
What happenes if we have a CPU with only one core? Will only one task run? Will the second tasks wait for the first thread to be available?
Edit: Let's say that Tasks 2 relies on Task 1 to be completed first. Will this always be the case on a single Core CPU?
int counter = 0;
TriggerHour1 = new TimeSpan(0, 1, 0);
Task.Run(async () =>
{
while (true)
{
var triggerTime = DateTime.Today + TriggerHour1 - DateTime.Now;
if (triggerTime < TimeSpan.Zero)
triggerTime = triggerTime.Add(new TimeSpan(24, 0, 0));
await Task.Delay(triggerTime);
Console.WriteLine("RunningTask1 finished");
counter += 100;
Console.WriteLine(counter);
}
});
TriggerHour2 = new TimeSpan(0, 1, 0);
Task.Run(async () =>
{
while (true)
{
var triggerTime = DateTime.Today + TriggerHour2 - DateTime.Now;
if (triggerTime < TimeSpan.Zero)
triggerTime = triggerTime.Add(new TimeSpan(24, 0, 0));
await Task.Delay(triggerTime);
Console.WriteLine("RunningTask2 finished");
Console.WriteLine(counter);
}
});
Will the first Task always run before?
First of all
Taskdoes not always mean there is a thread (see the There Is No Thread by Stephen Cleary), actually in this case both in theory can be served by one thread (due toawait Task.Delay(triggerTime)).As for threads on single core CPU - multithreading can be implemented on a single processor system, it is up for the OS how to schedule them, from Can multithreading be implemented on a single processor system?:
Also there are some hardware implementations like Intel's Hyper-threading which allows simulating multiple (usually 2) logical cores per one physical.
Yes.
If you have interdependencies between two parallel processes (threads, tasks, whatever) you need to use appropriate synchronization (see the overview of synchronization primitives), there are too many moving parts which can affect thigs - thread pool, OS scheduler, in your case system clock, in some cases memory model (How does CPU reorder instructions, memory ordering)
For example
counter += 100;is not a thread safe operation and if multiple threads perform updates tocounteryou can encounter quite unexpected results.