using System; using System.Threading; namespace ThreadDemo { class Program { static void Main(params string[] args) { Example4(args); Console.ReadKey(); } #region Example 0 Simple static void Example0(string[] args) { var t = new Thread(WriteY); t.Start(); for (int i = 0; i < 1000; i++) { Console.Write("x"); } } static void WriteY() { for (int i = 0; i < 1000; i++) { Console.Write("y"); } } #endregion #region Example 1 Join And Sleep /* Join : You can wait for another thread to end by calling its Join method Thread.Sleep: Pauses the current thread for a specified period */ static void Example1(string[] args) { var t = new Thread(WriteY); t.Start(); t.Join(); for (int i = 0; i < 1000; i++) { Console.Write("x"); } Console.WriteLine("Thread is sleeping 5 seconds"); Thread.Sleep(TimeSpan.FromSeconds(5)); Console.WriteLine("Waited 5 seconds"); } #endregion #region Example 2 If threads on same instance they can share fields. bool done; static void Example2(string[] args) { var td = new Program(); new Thread(td.Go).Start(); td.Go(); } void Go() { // it changed by another thread so it will write just once if (!done) { done = true; Console.WriteLine("Done"); } } #endregion #region Example 3 Locking and Thread Safety static readonly object _locker = new object(); static void Example3(string[] args) { var td = new Program(); new Thread(td.GoThreadSafe).Start(); td.GoThreadSafe(); } void GoThreadSafe() { // it will lock thread so other thread cannot acces until this operation finished finished lock (_locker) { if (!done) { done = true; Console.WriteLine("Done"); } } } #endregion #region Example 4 Signaling /*Sometimes you need a thread to wait until receiving notification(s) from other thread(s). This is called signaling. The simplest signaling construct is ManualReset Event. Calling WaitOne on a ManualResetEvent blocks the current thread until another thread “opens” the signal by calling Set. */ static void Example4(string[] args) { var signal = new ManualResetEvent(false); new Thread(() => { Console.WriteLine("Waiting for signal ..."); signal.WaitOne(); signal.Dispose(); Console.WriteLine("Got signal!"); }).Start(); Thread.Sleep(TimeSpan.FromSeconds(2)); signal.Set(); } #endregion } }