AutoResetEventでタイミング
AutoResetEventでスレッド間のタイミングをとることを練習中。
AutoResetEventを用いてタイミングをとりつつ、callbackデリゲートを実行している例。
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace TestThread { class Program { volatile static bool stopThread = false; static AutoResetEvent autoResetEvent = new AutoResetEvent(false); static AutoResetEvent autoResetEvent2 = new AutoResetEvent(false); delegate void dosomething(object arg); static dosomething callback; static object arg; static object lockObj = new object(); static void Main(string[] args) { Thread thread = new Thread(Run); thread.Start(); callback = new dosomething(something); for (int i = 0; i < 3; i++) { lock (lockObj) { arg = (object)i; autoResetEvent.Set(); autoResetEvent2.WaitOne(); } } stopThread = true; autoResetEvent.Set(); try { thread.Join(100); } catch (Exception) { } finally { thread.Abort(); } } static void Run() { while (!stopThread) { autoResetEvent.WaitOne(); if (!stopThread) callback(arg); autoResetEvent2.Set(); } return; } static void something(object arg) { Console.WriteLine("{0}: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, (int)arg); return; } } }