溫馨提示×

c# set怎樣確保線程安全

c#
小樊
132
2024-11-16 14:17:40
欄目: 編程語言

在C#中,要確保HashSet<T>的線程安全,可以使用ConcurrentDictionary<TKey, TValue>類來代替HashSet<T>。ConcurrentDictionary<TKey, TValue>是線程安全的,可以在多個線程之間安全地存儲和訪問鍵值對。

以下是一個使用ConcurrentDictionary<TKey, TValue>的示例:

using System;
using System.Collections.Concurrent;
using System.Threading;

class Program
{
    static ConcurrentDictionary<int, string> concurrentSet = new ConcurrentDictionary<int, string>();

    static void Main(string[] args)
    {
        Thread t1 = new Thread(() => AddToSet(1, "one"));
        Thread t2 = new Thread(() => AddToSet(2, "two"));
        Thread t3 = new Thread(() => AddToSet(3, "three"));

        t1.Start();
        t2.Start();
        t3.Start();

        t1.Join();
        t2.Join();
        t3.Join();

        Console.WriteLine("ConcurrentSet contains: " + string.Join(", ", concurrentSet));
    }

    static void AddToSet(int key, string value)
    {
        concurrentSet.AddOrUpdate(key, value, (k, v) => value);
    }
}

在這個示例中,我們使用ConcurrentDictionary<int, string>AddOrUpdate方法來添加或更新集合中的元素。這個方法會在添加新元素或更新現有元素時執行指定的操作。在這個例子中,我們只是簡單地將新值設置為舊值。

通過使用ConcurrentDictionary<TKey, TValue>,我們可以確保在多個線程之間對集合的操作是線程安全的。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女