Threadings Uses and Misuses.......... chapter 19..... class - TopicsExpress



          

Threadings Uses and Misuses.......... chapter 19..... class ThreadTest { static void Main( ) { Thread t = new Thread (WriteY); // Kick off a new thread t.Start(); // running WriteY( ) // Simultaneously, do something on the main thread. for (int i = 0; i < 1000; i++) Console.Write (x); } static void WriteY( ) { for (int i = 0; i < 1000; i++) Console.Write (y); } } // Output: xxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyy yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy yyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Tip All examples assume the following namespaces are imported, unless otherwise specified: using System; using System.Threading; You can wait for another thread to end by calling its Join method. Heres an example: static void Main( ) { Thread t = new Thread (Go); t.Start( ); t.Join( ); Console.WriteLine (Thread t has ended!); } static void Go( ) { for (int i = 0; i < 1000; i++) Console.Write (y); } Thread.Sleep (TimeSpan.FromHours (1)); // sleep for 1 hour Thread.Sleep (500); // sleep for 500 milliseconds Thread.Sleep (0); // relinquish CPU time-slice Console.WriteLine (Thread.CurrentThread.Name) Passing Data to a Thread Lets say we want to pass an argument to the method on which a thread starts. Heres how its done: static void Main( ) { Thread t = new Thread (Print); t.Start (Hello from t!); Print (Hello from the main thread!); } static void Print (object messageObj) { string message = (string) messageObj; Console.WriteLine (message); } // Output: Hello from t! Hello from the main thread!
Posted on: Sat, 22 Mar 2014 18:53:39 +0000

Trending Topics



Recently Viewed Topics




© 2015