2013-01-23 12 views
8

के साथ दो धागे सिंक्रनाइज़ करना मैं AutoResetEvent को लागू करने की कोशिश कर रहा हूं। इस उद्देश्य के लिए मैं एक बहुत ही सरल वर्ग का उपयोग करता हूं: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(); 
    } 
} 

लेकिन यह काम नहीं कर रहा है। उपयोग बहुत सीधी-आगे प्रतीत होता है, इसलिए अगर मैं किसी को यह दिखाने में सक्षम हूं कि क्या गलत है और तर्क के साथ समस्या कहां है, तो मैं सराहना करता हूं।

+0

कैसे यह नहीं है काम कर रहे? क्या होता है? – SLaks

+0

वैसे जो कोड आपने दिया है वह भी संकलित नहीं होगा - आपने कभी '_stopThreads' घोषित नहीं किया है ... –

+0

@ जॉन स्कीट मैं समस्या को अलग करने के लिए कोड बदलता हूं, अब यह तय हो गया है। – Leron

उत्तर

19

प्रश्न बहुत स्पष्ट नहीं है, लेकिन मैं आपको यह 1,2,1,2 प्रदर्शित करने के लिए उम्मीद कर रहे हैं अनुमान लगा रहा हूँ ...

फिर इस कोशिश:

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(); 
    } 
} 

 संबंधित मुद्दे

  • कोई संबंधित समस्या नहीं^_^