-4

if we have a ConcurrentBag<object> safeBag` filled with 100 objects.

then one thread works as:

   foreach(object o in safeBag)
{
    Thread.Sleep(1000);
}

the other thread starts right after the 1st thread starts:

{
    safeBag.AddOrTake(something);
}

Will the 2nd thread wait for 100Sec to enter the resource? Another question, if the 1st thread run with Parallel.ForEach(),how will the threads work?

EDIT:The MSDN said:"A List can support multiple readers concurrently, as long as the collection is not modified. Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration." Does the Enumerating through the ConcurrentBag cause the 2nd thread waiting at writing access to the ConcurrentBag?

4

2 に答える 2

0

2 番目のスレッドは、2 つのスレッドを連続して生成すると仮定します。最初のスレッドThreadStartは反復を含むブロックへのポインタを使用し、2 番目のスレッドはその他のコード ブロックへのポインタを使用し、1000 ミリ秒待機しません。foreachブロックはセット内の次のオブジェクトに移動するまで 1 秒間待機するだけで、2 番目のブロックは影響を受けません。

並列 foreach の場合、次の要素に移動する前に、複数のスレッドが (同時に) 1 秒間待機することになります。ConcurrentBag2 番目のブロックは、が解放されるのをまだ待っていません。

于 2012-10-26T09:14:15.480 に答える