ConcurrentBag.txt. https://docs.microsoft.com/zh-tw/dotnet/api/system.collections.concurrent.concurrentbag-1?view=netframework-4.8 命名空間: System.Collections.Concurrent 組件: System.Collections.Concurrent.dll, System.dll, netstandard.dll 代表安全執行緒的未排序物件集合。 [System.Runtime.InteropServices.ComVisible(false)] [System.Serializable] public class ConcurrentBag : System.Collections.Concurrent.IProducerConsumerCollection, System.Collections.Generic.IEnumerable, System.Collections.Generic.IReadOnlyCollection 下列範例顯示如何在 ConcurrentBag中新增和移除專案: using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; class ConcurrentBagDemo { // Demonstrates: // ConcurrentBag.Add() // ConcurrentBag.IsEmpty // ConcurrentBag.TryTake() // ConcurrentBag.TryPeek() static void Main() { // Add to ConcurrentBag concurrently ConcurrentBag cb = new ConcurrentBag(); List bagAddTasks = new List(); for (int i = 0; i < 500; i++) { var numberToAdd = i; bagAddTasks.Add(Task.Run(() => cb.Add(numberToAdd))); } // Wait for all tasks to complete Task.WaitAll(bagAddTasks.ToArray()); // Consume the items in the bag List bagConsumeTasks = new List(); int itemsInBag = 0; while (!cb.IsEmpty) { bagConsumeTasks.Add(Task.Run(() => { int item; if (cb.TryTake(out item)) { Console.WriteLine(item); itemsInBag++; } })); } Task.WaitAll(bagConsumeTasks.ToArray()); Console.WriteLine($"There were {itemsInBag} items in the bag"); // Checks the bag for an item // The bag should be empty and this should not print anything int unexpectedItem; if (cb.TryPeek(out unexpectedItem)) Console.WriteLine("Found an item in the bag when it should be empty"); } } 備註 當順序不重要時,包可用於儲存物件,而不同于集合,包則支援重複專案。 ConcurrentBag 是安全線程包的執行,針對相同執行緒同時產生和取用儲存在包中的資料的案例進行優化。 ConcurrentBag 接受 null 作為參考型別的有效值。