using System;
using System.Collections.Generic;
using System.Text;
using LogHandler;
using System.Threading;
namespace ConsoleApplication5
{
class Program
{
private static List<string> lstShare = new List<string>();
static void Main(string[] args)
{
Thread th1 = new Thread(thread1);
th1.Start();
Thread th2 = new Thread(thread2);
th2.Start();
}
private static void thread1()
{
//該線程不停地獨占列表,並追加數據
while (true)
{
lock (lstShare)
{
lstShare.Add("aaa");
}
}
}
private static void thread2()
{
//該線程是期望創建一個共享列表的獨立鏡像,然后對鏡像進行費時的操作
while (true)
{
try
{
List<string> lstTemp = new List<string>();
lock (lstShare)
{
lstTemp = lstShare;//如果使用這一句來創建鏡像,就會發生異常
#region "正確的做法"
//foreach (string item in lstShare)
//{
// lstTemp.Add(item);
//}
#endregion
}
foreach (string item in lstTemp)
{
//do nothing
Thread.Sleep(1);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}