且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用不同的参数调用相同的方法 - 如何使用多线程/并行类?

更新时间:2023-01-04 17:35:39

多线程或并行可能会或可能不会加速 - 它实际上可以减慢因为处理设置线程/任务并为它们分配单独的内存空间的开销。此外,它还取决于其他内容 - 如果每个线程需要与SQL交谈,那么每个线程可能会使用两个内核。



我会做的第一件事看看你有什么,并开始计时。 (使用秒表类)尝试找出操作的哪个部分需要时间,可能是您可以进行简单的更改,从而大大减少操作。例如,如果您为进入列表的每个项目访问数据库,那么您可能会发现单次旅行更快,然后将数据排序。至少如果你已经计算出每个部分需要多长时间,你可以定位你的变化,并量化它们是否值得解决。



(我有一个在启动时从数据库加载的列表,使用后台任务和启动画面加载1000多个项目花了两分半钟。通过计算浪费时间的时间,我把它减少到12秒,30,000个项目,并抛弃了飞溅)
Multithreading or parallel may or may not speed things up - it can actually slow things down because of the processing overhead in setting up the thread / tasks and allocating separate memory space for them. In addition it depends what else is going on - if each thread needs to talk to SQL then that will potentially use two cores per thread.

The first thing I would do is look at what you have, and start timing it. (Use the Stopwatch class) Try to find which part of the operation is taking time, it may be that you can make a simple change which cuts it dramatically. For example, if you are doing a trip to your DB for each item going into the list, then you may find it a lot quicker to do a single trip then sort the data out afterwards. At least if you have worked out how long each part takes, you can both target your changes, and quantify them as to whether they are worthwhile solutions or not.

(I had a list which loaded from a database on startup, and it took two and half minutes to load 1000+ items using a background task and a splash screen. By timing what was wasting time, I got it down to 12 seconds for 30,000 items, and dumped the splash)