Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 线程安全的list

作者:/神經病/   发布日期:2026-01-14   浏览:103

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);
        }
    }
}

解释说明:

  1. ConcurrentBagConcurrentBag<T> 是 .NET 提供的一个线程安全的集合类,适用于在多线程环境中进行高效的添加和移除操作。它不像 List<T> 那样需要额外的同步机制来保证线程安全。

  2. 线程创建与启动:我们创建了多个线程,并在每个线程中向 ConcurrentBag 添加一个整数。由于 ConcurrentBag 是线程安全的,因此不需要担心并发访问时的数据竞争问题。

  3. 等待线程完成:使用 Thread.Join() 方法确保主线程等待所有子线程完成后再继续执行。

  4. 输出结果:最后遍历并输出 ConcurrentBag 中的所有元素。请注意,ConcurrentBag 不保证元素的顺序,因为它是为了高性能而设计的,而不是为了保持插入顺序。

上一篇:c# tree

下一篇:rabbitmq c#

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站