gpt4 book ai didi

.net - ThreadPool.QueueUserWorkItem与Parallel.For

转载 作者:行者123 更新时间:2023-12-03 13:12:47 26 4
gpt4 key购买 nike

我试图了解Parralel.ForThreadPool.QueueUserWorkItem之间的区别。

硬件和软件:

  • 英特尔i5(四核)
  • Windows 7 64位教授
  • DotNet 4.5

  • 案例1代码:ThreadPool
    for (int index = 0; index < 5; index++)
    {
    ThreadPool.QueueUserWorkItem((indexParam) =>
    {
    int threadID = Thread.CurrentThread.ManagedThreadId;
    Thread.Sleep(1000);
    BeginInvoke((Action)delegate { listBox1.Items.Add("Completed " + indexParam.ToString() + " using thread " + threadID.ToString() + " (" + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString("000") + ")"); });
    }, index);
    }

    输出:

    Completed 0 using thread 10 (45.871)
    Completed 1 using thread 11 (45.875)
    Completed 2 using thread 12 (45.875)
    Completed 3 using thread 13 (45.875)
    Completed 4 using thread 10 (46.869)



    情况2代码:Parallel.For
      ParallelLoopResult result = Parallel.For(0, 5, (int index, ParallelLoopState loopState) =>
    {
    int threadID = Thread.CurrentThread.ManagedThreadId;
    Thread.Sleep(1000);
    BeginInvoke((Action)delegate { listBox1.Items.Add("Completed " + index.ToString() + " using thread " + threadID.ToString() + " (" + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString("000") + ")"); });
    });

    输出:

    Completed 0 using thread 10 (16.923)
    Completed 1 using thread 11 (16.925)
    Completed 2 using thread 12 (16.925)
    Completed 3 using thread 13 (16.926)
    Completed 4 using thread 14 (16.926)



    问题:

    从案例1的结果来看,似乎只有四个线程处于 Activity 状态,然后使用第一个空闲线程来完成最终任务。在情况2中,似乎有五个线程被立即专用并“同时”执行。
    为什么QueueUserWorkItem的线程处理不像并行类那样不使用第五个线程?
    (ThreadPool.GetAvailableThreads(...)确认1023个工作线程可用)。

    最佳答案

    我相信“ Activity ”线程和“可用”线程之间是有区别的。线程池将重用线程,如果它决定需要更多线程,它将开始将可用线程移到 Activity 线程。如果您想一次启动很多东西,这可能会令人沮丧,因为每个可用线程可能需要大约2秒钟才能启动。

    MSDN Managed Threadpool

    As part of its thread management strategy, the thread pool delays before creating threads. Therefore, when a number of tasks are queued in a short period of time, there can be a significant delay before all the tasks are started.



    如果要重复运行这些任务或添加任务,则应该看到其他线程处于 Activity 状态。

    关于.net - ThreadPool.QueueUserWorkItem与Parallel.For,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20686334/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com