我在這裏做的是在多線程中通過for-each和index方法導航一個只讀列表。結果看起來線程安全,但我不相信。 有沒有人可以告訴下面的代碼(從只讀列表中讀取)是否線程安全?如果是的話,爲什麼C#只讀列表線程同步
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();
}
}
解釋爲什麼你認爲它不是線程安全的。 – 2014-10-17 00:06:36