我一直在下面的代碼中發現內存不足異常,我想知道是否有什麼我可以做,以阻止這種情況發生。線程池內存異常
private static List<string> MyIds { get; set; }
private static object LockObject { get; set; }
private static int Counter { get; set; }
private static readonly NumOfThreads = 5;
static void Main(string[] args)
{
try
{
Console.Clear();
LockObject = new object();
// Pull id's into memory (A list of around 1 million ids)
MyIds = _repository.GetIds();
for (int i = 0; i < NumOfThreads ; i++)
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), (object)i);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
public static void DoWork(Object stateInfo)
{
while (MyList.Count > 0)
{
lock (LockObject)
{
if (MyList.Count == 0)
return;
string id = MyList[0];
var record = _repository.GetRecord(id);
_repository.Add(record);
Counter++;
if (Counter % 100 == 0)
System.Console.WriteLine(DateTime.Now + " - Imported " + Counter.ToString() + " Records..");
MyList.RemoveAt(0);
}
}
}
感謝所有幫助
很少有觀察結果與OOM無關。 1.您正在序列化訪問DoWork中的所有代碼,因此使用多個線程沒有意義。 2.您沒有使用傳入的stateInfo值。 3.您在鎖外訪問MyList,以便此訪問不是線程安全的。 – 2010-12-13 21:24:25