为什么不抛出异常

本文关键字:抛出异常 为什么不 | 更新日期: 2023-09-27 18:36:56

当我运行下一个代码时,抛出一个 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
}

但是,如果我在"ThreadProc"方法中创建流 - 没有例外:

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
}

为什么会有区别?

为什么不抛出异常

因为第一个总是分配循环中的所有内存流。

seond 仅在线程运行时分配它们。由于您在线程池中运行,因此它们不会一次全部运行