当我运行下一个代码时,抛出OutOfMemoryException:
static void Main(string[] args)
{
for (int i = 0; i < 200; i++)
{
Stream filestream = new MemoryStream(Resources.File); // Resources.File is typeof byte[]
ThreadPool.QueueUserWorkItem(ThreadProc, filestream);
}
Thread.Sleep(999999999);
}
private static void ThreadProc(object stream)
{
// Document is 3rd party's class
Document doc = new Document((Stream)stream); // OutOfMemoryException is thrown after 160 iterations
}
但是,如果我在&#34; ThreadProc&#34;中创建了Stream。方法 - 没有例外:
static void Main(string[] args)
{
for (int i = 0; i < 200; i++)
{
ThreadPool.QueueUserWorkItem(ThreadProc, null);
}
Thread.Sleep(999999999);
}
private static void ThreadProc(object stream)
{
Stream filestream = new MemoryStream(Resources.File);
Document doc = new Document(filestream); // Exception is NOT thrown
}
为什么会有区别?
答案 0 :(得分:6)
因为第一个总是在循环中分配所有内存流。
seond one只在线程运行时分配它们。由于您在线程池中运行,因此它们不会立即运行