2013-01-23 11 views
8

sto cercando di implementare AutoResetEvent. Per lo scopo uso una classe molto semplice:Sincronizzazione dei due fili con AutoResetEvent

public class MyThreadTest 
{ 
    static readonly AutoResetEvent thread1Step = new AutoResetEvent(false); 
    static readonly AutoResetEvent thread2Step = new AutoResetEvent(false); 

    void DisplayThread1() 
    { 
     while (true) 
     { 
      Console.WriteLine("Display Thread 1"); 

      Thread.Sleep(1000); 
      thread1Step.Set(); 
      thread2Step.WaitOne(); 
     } 
    } 

    void DisplayThread2() 
    { 
     while (true) 
     { 
      Console.WriteLine("Display Thread 2"); 
      Thread.Sleep(1000); 
      thread2Step.Set(); 
      thread1Step.WaitOne(); 
     } 
    } 

    void CreateThreads() 
    { 
     // construct two threads for our demonstration; 
     Thread thread1 = new Thread(new ThreadStart(DisplayThread1)); 
     Thread thread2 = new Thread(new ThreadStart(DisplayThread2)); 

     // start them 
     thread1.Start(); 
     thread2.Start(); 
    } 

    public static void Main() 
    { 
     MyThreadTest StartMultiThreads = new MyThreadTest(); 
     StartMultiThreads.CreateThreads(); 
    } 
} 

Ma questo non funziona. L'uso mi sembra molto semplice, quindi sarei grato se qualcuno sia in grado di mostrarmi cosa c'è che non va e dove si trova il problema con la logica che implemento qui.

+0

Come non è vero lavoro? Che succede? – SLaks

+0

Bene il codice che hai dato non sarà nemmeno la compilazione - non hai mai dichiarato '_stopThreads' ... –

+0

@ Jon Skeet mi limito a cambiare il codice per isolare il problema, ora è risolto. – Leron

risposta

19

la questione non è molto chiaro, ma sto cercando di indovinare ci si aspetta che venga visualizzato 1,2,1,2 ...

quindi provare questo:

public class MyThreadTest 
{ 
    static readonly AutoResetEvent thread1Step = new AutoResetEvent(false); 
    static readonly AutoResetEvent thread2Step = new AutoResetEvent(true); 

    void DisplayThread1() 
    { 
     while (true) 
     { 
      thread2Step.WaitOne(); 
      Console.WriteLine("Display Thread 1"); 
      Thread.Sleep(1000); 
      thread1Step.Set(); 
     } 
    } 

    void DisplayThread2() 
    { 
     while (true) 
     { 
      thread1Step.WaitOne(); 
      Console.WriteLine("Display Thread 2"); 
      Thread.Sleep(1000); 
      thread2Step.Set(); 
     } 
    } 

    void CreateThreads() 
    { 
     // construct two threads for our demonstration; 
     Thread thread1 = new Thread(new ThreadStart(DisplayThread1)); 
     Thread thread2 = new Thread(new ThreadStart(DisplayThread2)); 

     // start them 
     thread1.Start(); 
     thread2.Start(); 
    } 

    public static void Main() 
    { 
     MyThreadTest StartMultiThreads = new MyThreadTest(); 
     StartMultiThreads.CreateThreads(); 
    } 
}