44
loading...
This website collects cookies to deliver better user experience
public static class Example
{
public static void Main()
{
// Here starts the main program flow.
Console.WriteLine("Do this first");
Console.WriteLine("Do this second");
// The main program flow ends once the main returns.
}
}
public static void Main()
{
// Here starts the main program flow.
Thread worker = new Thread(() =>
{
// Sleep the worker thread for 100 milliseconds.
Thread.Sleep(100);
Console.WriteLine("Worker Thread: Woke up");
});
// Start a worker thread and execute the work
// asynchronously.
worker.Start();
Thread.Sleep(100);
Console.WriteLine("Main Thread: Woke up");
// Block the main thread until the worker completes.
worker.Join();
Console.WriteLine("Main Thread: Do this last");
// The main program flow ends once the main returns.
}
Main Thread: Woke up
Worker Thread: Woke up
Main Thread: Do this last
public static void Main()
{
int workerRanFirstCount = 0;
int mainRanFirstCount = 0;
int totalRuns = 10;
var runOrder = new ConcurrentQueue<string>();
var workers = new List<Thread>();
for (int ii = 0; ii < totalRuns; ++ii)
{
workers.Add(new Thread(() =>
{
Thread.Sleep(100);
runOrder.Enqueue("worker");
}));
}
foreach (var worker in workers)
{
worker.Start();
Thread.Sleep(100);
runOrder.Enqueue("main");
// Block the main thread until the worker completes.
worker.Join();
if (runOrder.First() == "worker") ++workerRanFirstCount;
if (runOrder.First() == "main") ++mainRanFirstCount;
runOrder.Clear();
}
Console.WriteLine($"Main ran first count = {mainRanFirstCount}; Worker ran first = {workerRanFirstCount}");
}
Main ran first count = 10; Worker ran first = 0
Main ran first count = 8; Worker ran first = 2
Main ran first count = 6; Worker ran first = 4