ForEach之间的区别

ForEach之间的区别

本文介绍了ThreadPool.QueueUserWorkItem和Parallel.ForEach之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ThreadPool.QueueUserWorkItem

以下办法两者之间的主要区别是什么b

ThreadPool.QueueUserWorkItem

    Clients objClient = new Clients();
    List<Clients> objClientList = Clients.GetClientList();

    foreach (var list in objClientList)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(SendFilesToClient), list);
    }



System.Threading.Tasks.Parallel的ForEach

    Clients objClient = new Clients();
    List<Clients> objClientList = Clients.GetClientList();

    Parallel.ForEach<Clients>(objClientList, list =>
    {
        SendFilesToClient(list);
    });



我是新来的多线程,想知道发生了什么事在每种情况下发生(在条款执行过程中的)什么是多线程的每种方法的水平? 。帮助我想象这两个过程

I am new to multi-threading and want to know what's going to happen in each case (in terms of execution process) what's the level of multi-threading for each approach? Help me visualize both the processes.

SendFilesToClient:从数据库中获取的数据,转换成Excel和发送的Excel文件到相应的客户端。

SendFilesToClient: Gets data from database, converts to Excel and sends the Excel file to respective client.

谢谢!

推荐答案

的主要区别是功能性的。 Parallel.ForEach 将阻止(设计),所以它不会返回,直到所有的对象都已经被处理。你的的foreach 排队线程池线程的工作将工作推到后台线程,并没有阻止。

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.

此外, Parallel.ForEach 版本将有另一个主要优点 - 未处理的异常将被推迟到调用点这里,而不是在一个线程池线程离开未处理

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.

在一般情况下, Parallel.ForEach 将更有效率。这两种方法都使用线程池,但 Parallel.ForEach 做智能分区,以防止overthreading并减少开销由调度所需的时间。各个任务(其中将映射到线程池线程)被重用,并且有效地集中开销降低,特别是当 SendFilesToClient 是一个快速的操作(其中,在这种情况下,将。不是真的)

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).

请注意,您也可以,作为第三个选项,请使用PLINQ:

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

objClientList.AsParallel().ForAll(SendFilesToClient);

这将是非常相似的 Parallel.ForEach 方法的性能和功能方面。

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

这篇关于ThreadPool.QueueUserWorkItem和Parallel.ForEach之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:07