Skip to content

Instantly share code, notes, and snippets.

@kevingosse
Last active June 26, 2019 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevingosse/45e87d1492b0cacae36a2ac8b1d85e19 to your computer and use it in GitHub Desktop.
Save kevingosse/45e87d1492b0cacae36a2ac8b1d85e19 to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
private static Task _sharedTask;
static void Main(string[] args)
{
var tcs = new TaskCompletionSource<bool>();
_sharedTask = tcs.Task;
Task.Run(Thread1);
Thread.Sleep(1000); // Wait for the task to start
Task.Run(Thread2);
Thread.Sleep(1000); // Wait for the task to start
Task.Run(() => Thread3());
Thread.Sleep(1000); // Wait for the task to start
Console.WriteLine("Shared task completed at {0}", DateTime.Now.ToLongTimeString());
tcs.SetResult(true);
Console.ReadLine();
}
private static async Task Thread1()
{
await _sharedTask;
// Simulate some work
Thread.Sleep(10000);
Console.WriteLine("Thread1 completed at {0}", DateTime.Now.ToLongTimeString());
}
private static async Task Thread2()
{
await _sharedTask;
// No additional work, this task is expected to complete quickly
Console.WriteLine("Thread2 completed at {0}", DateTime.Now.ToLongTimeString());
}
private static void Thread3()
{
_sharedTask.ContinueWith(_ =>
{
// No additional work, this task is expected to complete quickly
Console.WriteLine("Thread3 completed at {0}", DateTime.Now.ToLongTimeString());
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment