using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
class Program
{
static void Main()
{
// 使用 ConcurrentBag,它是线程安全的集合
ConcurrentBag<int> threadSafeList = new ConcurrentBag<int>();
// 创建多个线程并添加元素到线程安全的列表中
List<Thread> threads = new List<Thread>();
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(() => threadSafeList.Add(i));
threads.Add(t);
t.Start();
}
// 等待所有线程完成
foreach (Thread t in threads)
{
t.Join();
}
// 输出线程安全列表中的元素
Console.WriteLine("线程安全列表中的元素:");
foreach (var item in threadSafeList)
{
Console.WriteLine(item);
}
}
}
ConcurrentBag:ConcurrentBag<T> 是 .NET 提供的一个线程安全的集合类,适用于在多线程环境中进行高效的添加和移除操作。它不像 List<T> 那样需要额外的同步机制来保证线程安全。
线程创建与启动:我们创建了多个线程,并在每个线程中向 ConcurrentBag 添加一个整数。由于 ConcurrentBag 是线程安全的,因此不需要担心并发访问时的数据竞争问题。
等待线程完成:使用 Thread.Join() 方法确保主线程等待所有子线程完成后再继续执行。
输出结果:最后遍历并输出 ConcurrentBag 中的所有元素。请注意,ConcurrentBag 不保证元素的顺序,因为它是为了高性能而设计的,而不是为了保持插入顺序。
上一篇:c# tree
下一篇:rabbitmq c#
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站