2013-01-23 37 views
8

Tôi đang cố triển khai AutoResetEvent. Vì mục đích tôi sử dụng một lớp học rất đơn giản:Đồng bộ hóa hai chuỗi với 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(); 
    } 
} 

Nhưng điều này không hiệu quả. Th sử dụng có vẻ rất thẳng về phía trước vì vậy tôi sẽ đánh giá cao nếu ai đó có thể cho tôi thấy những gì là sai và đâu là vấn đề với logic mà tôi thực hiện ở đây.

+0

Làm thế nào là nó không đang làm việc? Chuyện gì xảy ra? – SLaks

+0

Vâng mã bạn đã đưa ra thậm chí sẽ không biên dịch - bạn chưa bao giờ khai báo '_stopThreads' ... –

+0

@ Jon Skeet Tôi chỉ thay đổi mã để tách biệt vấn đề, bây giờ nó đã được sửa. – Leron

Trả lời

19

Câu hỏi đặt ra không phải là rất rõ ràng nhưng tôi đoán bạn đang mong nó để hiển thị 1,2,1,2 ...

Sau đó thử này:

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(); 
    } 
} 
Các vấn đề liên quan