ManualResetEvent

スレッド間のやりとりを実現する。
下記の例では、スレッドBはスレッドAの処理が終わるまで待機する。
MSDNにManualResetEventの配列を使ったサンプルがある。

また、WaiteOne()後のリセットを自動で行ってくれる。AutoResetEventクラスも存在する。
考え方・使い方はManualと同じなのでコード例は省略。

public partial class Form1 : Form
{
    private int count = 0;
    private readonly Object locker = new Object();
    private ManualResetEvent m_event = new ManualResetEvent(true);

    public Form1()
    {
        InitializeComponent();
    }

    private void threadFunc(Object param)
    {
        String thdName = (String)param;

        lock (locker)
        {
            m_event.WaitOne();//シグナル状態になるまで待機
            m_event.Reset();//非シグナル状態にセット。他のスレッドがWaitOne()で待機になる。
        }

        for(int i=0;i<1000;i++)
        {
            Console.WriteLine("スレッド:{0}、カウント値:{1}", thdName, count);
            count++;
        }

        m_event.Set();//他スレッドの待機状態を解除。シグナル状態にセットする。
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread thdA = new Thread(new ParameterizedThreadStart(threadFunc));
        Thread thdB = new Thread(new ParameterizedThreadStart(threadFunc));

        thdA.Start((Object)"スレッドA");
        thdB.Start((Object)"スレッドB");
    }
}