Last active
June 26, 2019 18:30
-
-
Save kevingosse/45e87d1492b0cacae36a2ac8b1d85e19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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