如何设置线程数Parallel.ForEach [英] How set thread count Parallel.ForEach

查看:412
本文介绍了如何设置线程数Parallel.ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了10个线程数,但是它可以在3个线程中工作.(我有三核处理器)

I set number of thread 10, but it works in 3 threads.(I have triple-core processor)

Parallel.ForEach(list,
new ParallelOptions { MaxDegreeOfParallelism = 10 },
                () => Thread.CurrentThread.ManagedThreadId,
                (i, loopState, threadId) =>
                {
                    var cells = i.Split(';');
                    var ip = cells[0];
                    var login = cells[1];
                    var pass = cells[2];
                    try
                    {
                        using (var client = new SshClient(ip, login, pass))
                        {
                            client.Connect();
                            var port = new ForwardedPortLocal("localhost", 10000 + (uint)threadId, "ya.ru", 80);
                            port.Start();
                            client.AddForwardedPort(port);
                            newList.Add(ip);
                            port.Stop();
                            client.Disconnect();
                        }
                    }
                    catch
                    {


                    }

                    return threadId;
                },
                (t

hreadId) => { }

推荐答案

MaxDegreeOfParallelism 的用途限制最多可以使用多少个线程.这并不意味着系统将使用多个线程.

决定使用多少线程. TaskScheduler [ ^ ].您可以使用默认的调度程序,也可以创建自己的调度程序,但是从我的角度来看,标准调度程序通常可以做出明智的决定.
The purpose of MaxDegreeOfParallelism is only to restrict how many threads can be used in maximum. It doesn''t meant that the system will use s many threads.

The decision how many threads are used is done by the TaskScheduler[^]. You can either stick with the default scheduler or create your own, but from my point of view the standard scheduler is usually making good decisions.


这篇关于如何设置线程数Parallel.ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆