Difference between ThreadPool.QueueUserWorkItem and Parallel.ForEach?

后端 未结 1 496
无人及你
无人及你 2021-02-07 00:46

What is the main difference between two of following approaches:

ThreadPool.QueueUserWorkItem

    Clients objClient = new Clients();
            


        
1条回答
  •  攒了一身酷
    2021-02-07 01:21

    The main difference is functional. Parallel.ForEach will block (by design), so it will not return until all of the objects have been processed. Your foreach queuing threadpool thread work will push the work onto background threads, and not block.

    Also, the Parallel.ForEach version will have another major advantages - unhandled exceptions will be pushed back to the call site here, instead of left unhandled on a ThreadPool thread.

    In general, Parallel.ForEach will be more efficient. Both options use the ThreadPool, but Parallel.ForEach does intelligent partitioning to prevent overthreading and to reduce the amount of overhead required by the scheduler. Individual tasks (which will map to ThreadPool threads) get reused, and effectively "pooled" to lower overhead, especially if SendFilesToClient is a fast operation (which, in this case, will not be true).

    Note that you can also, as a third option, use PLINQ:

    objClientList.AsParallel().ForAll(SendFilesToClient);
    

    This will be very similar to the Parallel.ForEach method in terms of performance and functionality.

    0 讨论(0)
提交回复
热议问题