gpt4 book ai didi

C# Readonly List 线程同步

转载 作者:行者123 更新时间:2023-12-03 12:52:20 27 4
gpt4 key购买 nike

我在这里所做的是通过 for-each 和索引方法在多个线程中导航只读列表。结果看起来线程安全,但我不相信。

有人可以告诉下面的代码(从只读列表中读取)是否是线程安全的吗?如果是的话为什么?

public class ThreadTest
{
readonly List<string> port;

public ThreadTest()
{
port = new List<string>() { "1", "2", "3", "4", "5", "6" };
}

private void Print()
{
foreach (var itm in port)
{
Thread.Sleep(50);
Console.WriteLine(itm+"----"+Thread.CurrentThread.ManagedThreadId);
}
}

private void Printi()
{
for(int i=0;i<5;i++)
{
Thread.Sleep(100);
Console.WriteLine(port[i] + "--iiiii--" + Thread.CurrentThread.ManagedThreadId);
}
}

public void StartThread()
{
Task[] tsks = new Task[10];
tsks[0] = new Task(Print);
tsks[1] = new Task(Print);
tsks[2] = new Task(Print);
tsks[3] = new Task(Print);
tsks[4] = new Task(Print);
tsks[5] = new Task(Printi);
tsks[6] = new Task(Printi);
tsks[7] = new Task(Printi);
tsks[8] = new Task(Printi);
tsks[9] = new Task(Printi);

foreach (var tsk in tsks)
{
tsk.Start();
}

Task.WaitAll(tsks);
}
}

class Program
{
static void Main(string[] args)
{

new ThreadTest().StartThread();

Console.ReadLine();
}
}

最佳答案

让多个线程从 List<T> 的同一个实例读取数据被认为是线程安全的。仅当没有作家时。

Thread Safety

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

It is safe to perform multiple read operations on a List, but issues can occur if the collection is modified while it’s being read. To ensure thread safety, lock the collection during a read or write operation. To enable a collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. For collections with built-in synchronization, see the classes in the System.Collections.Concurrent namespace. For an inherently thread–safe alternative, see the ImmutableList class.

重点是我的。

http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

关于C# Readonly List 线程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26415336/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com