何らかの理由で、.NET 3.5 に固執する必要があり、.NET 4 の Barrier クラスの機能が必要です。いくつかの作業を行うスレッドがたくさんあり、すべてが完了するまで相互に待機する必要があります。すべてが終わったら、同じように何度も何度もやってもらいたいと思います。C# 4.0 の Barrier と C# 3.0 の WaitHandle の違いというスレッドに励まされていますか? AutoResetEvent クラスと WaitHandle クラスを使用して Barrier 機能を実装することにしました。私のコードで問題が発生しましたが:
class Program
{
const int numOfThreads = 3;
static AutoResetEvent[] barrier = new AutoResetEvent[numOfThreads];
static Random random = new Random(System.DateTime.Now.Millisecond);
static void barriers2(object barrierObj)
{
AutoResetEvent[] barrierLocal = (AutoResetEvent[])barrierObj;
string name = Thread.CurrentThread.Name;
for (int i = 0; i < 10; i++)
{
int sleepTime = random.Next(2000, 10000);
System.Console.Out.WriteLine("Thread {0} at the 'barrier' will sleep for {1}.", name, sleepTime);
Thread.Sleep(sleepTime);
System.Console.Out.WriteLine("Thread {0} at the 'barrier' with time {1}.", name, sleepTime);
int currentId = Convert.ToInt32(name);
//for(int z = 0; z < numOfThreads; z++)
barrierLocal[currentId].Set();
WaitHandle.WaitAll(barrier);
/*
for (int k = 0; k < numOfThreads; k++)
{
if (k == currentId)
{
continue;
}
System.Console.Out.WriteLine("Thread {0} is about to wait for the singla from thread: {1}", name, k);
barrierLocal[k].WaitOne();
System.Console.Out.WriteLine("Thread {0} is about to wait for the singla from thread: {1}. done", name, k);
}
*/
}
}
static void Main(string[] args)
{
for (int i = 0; i < numOfThreads; i++)
{
barrier[i] = new AutoResetEvent(false);
}
for (int i = 0; i < numOfThreads; i++)
{
Thread t = new Thread(Program.barriers2);
t.Name = Convert.ToString(i);
t.Start(barrier);
}
}
}
私が受け取る出力は次のとおりです。
「バリア」のスレッド 0 は 7564 の間スリープします 「バリア」のスレッド 1 は 5123 の間スリープします 「バリア」のスレッド 2 は 4237 の間スリープします 「バリア」のスレッド 2 は時間 4237 で「バリア」のスレッド 1時間 5123 で 'バリア' のスレッド 0 時間 7564 'バリア' でのスレッド 0 は 8641 時間スリープします 'バリア' でのスレッド 0 時間 8641
以上です。最後の行の後、それ以上の出力はなく、アプリは終了しません。ある種の行き詰まりがあるようです。ただし、問題が見つかりません。どんな助けでも大歓迎です。
ありがとう!