// // Sample code for book "C# in Front Office" (ISBN/EAN13: 144215358X / 9781442153585) // // Code is provided as it is and without any guarentee. Using this code for both // personal and commercial purpose is permitted if the original source of this // code is included. // // Author email: greenwich2greenwich@gmail.com // Book website: http://book.greenwich2greenwich.com/CsInFrontOffice/ // Code Example: http://book.greenwich2greenwich.com/Examples/ // using System; using System.Threading; /// /// Creates a console application project and copies/pastes the following code. /// /// Executing this code multiple times will produce different results which is expected /// result from a multi-threaded application. /// public class ThreadingSample { static void Main(string[] args) { MyWorker w1 = new MyWorker("Tom"); MyWorker w2 = new MyWorker("Bob"); Thread t1 = new Thread(new ThreadStart(w1.DoJob)); Thread t2 = new Thread(new ThreadStart(w2.DoJob)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); Console.WriteLine("Done."); } } public class MyWorker { public MyWorker(String name_) { myName = name_; } public void DoJob() { for (int ii = 0; ii < 10; ++ii) { Console.WriteLine(String.Format("{0} is working ...", myName)); Thread.Sleep((int)(myRandom.NextDouble() * 5)); } } private String myName; private Random myRandom = new Random(); }