System.Collections.Concurrent

定义

提供线程安全集合相关类型

描述

包含用于多线程环境的线程安全集合类,如 ConcurrentDictionary、ConcurrentQueue 等

参数

参数名 类型 描述
key TKey
value TValue

返回值

返回值 类型 描述
success bool 操作是否成功

示例

示例代码,使用 ConcurrentDictionary:
using System.Collections.Concurrent;
using System.Threading.Tasks;
class Program {
    static void Main() {
        ConcurrentDictionary<int, string> dict = new ConcurrentDictionary<int, string>();
        Task[] tasks = new Task[10];
        for (int i = 0; i < 10; i++) {
            int index = i;
            tasks[i] = Task.Run(() => {
                dict.TryAdd(index, $"Value{index}");
            });
        }
        Task.WaitAll(tasks);
        foreach (var item in dict) {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}