Csharp/CSharp Tutorial/Thread/Thread Start — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 18:31, 26 мая 2010

An alternate way to start a thread: start a thread in its own constructor

<source lang="csharp">using System; using System.Threading;

class MyThread {

 public int count; 
 public Thread thrd; 

 public MyThread(string name) { 
   count = 0; 
   thrd = new Thread(this.run);
   thrd.Name = name; 
   thrd.Start(); 
 } 

 void run() { 
   Console.WriteLine(thrd.Name + " starting."); 

   do { 
     Thread.Sleep(500); 
     Console.WriteLine("In " + thrd.Name + 
                       ", count is " + count); 
     count++; 
   } while(count < 10); 

   Console.WriteLine(thrd.Name + " terminating."); 
 } 

}

class MainClass {

 public static void Main() { 
   Console.WriteLine("Main thread starting."); 

   MyThread mt = new MyThread("Child #1"); 

   do { 
     Console.Write("."); 
     Thread.Sleep(100); 
   } while (mt.count != 10); 

   Console.WriteLine("Main thread ending."); 
 } 

}</source>

Main thread starting.
Child #1 starting.
.....In Child #1, count is 0
.....In Child #1, count is 1
....In Child #1, count is 2
.....In Child #1, count is 3
....In Child #1, count is 4
.....In Child #1, count is 5
.....In Child #1, count is 6
....In Child #1, count is 7
.....In Child #1, count is 8
....In Child #1, count is 9
Child #1 terminating.
Main thread ending.

Simple Thread with ThreadStart

<source lang="csharp">using System; using System.Threading; class MainClass {

 public static void DoCount()
 {
   for ( int i = 0; i < 10; i++ )
   {
     System.Console.WriteLine( "Reached {0}", i );
   }
 }
 [STAThread]
 static void Main(string[] args)
 {
   Thread t = new Thread( new ThreadStart( DoCount ) );
   t.Start();
 }

}</source>

Reached 0
Reached 1
Reached 2
Reached 3
Reached 4
Reached 5
Reached 6
Reached 7
Reached 8
Reached 9

thread.IsAlive

<source lang="csharp">using System; using System.Threading; public class ThreadState {

   static void WorkerFunction() {
       for (int i = 1; i < 50000; i++) {
           Console.WriteLine("Worker: " + Thread.CurrentThread.ThreadState);
       }
   }
   static void Main() {
       string ThreadState;
       Thread t = new Thread(new ThreadStart(WorkerFunction));
       t.Start();
       while (t.IsAlive) {
           Console.WriteLine("Still waiting. I"m going back to sleep.");
           Thread.Sleep(200);
       }
       Console.WriteLine(t.ThreadState);
   }

}</source>