如何将parallel.foreach转换为threadpool [英] How to convert parallel.foreach to threadpool

查看:70
本文介绍了如何将parallel.foreach转换为threadpool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想将parallel.foreach转换为threadpool,因为我可以使用threadpool指定线程数量,而我无法使用parallel.foreach.Here是我的代码:

So I want to convert parallel.foreach to threadpool because I can specify amount of threads with threadpool and I cannot do it with parallel.foreach.Here is my code:

static Regex idcheck = new Regex(@"id"":""(.+?)"",");
        static Regex Migrationcheck = new Regex(@"legacy"":(.+?)}");
        static Regex Hashemailfinder = new Regex(":(.+?):");




        private static String _outputFileUnmigrated = "Unmigrated.txt";
        private static String _outputFileMigrated = "Migrated.txt";
        private static String _outputFileAvailable = "Available.txt";
        private static String _outputValidationLog = "ValidationLog.txt";
        private static String _outputUnmigratedGood = "UnmigratedGood.txt";
        private static String _outputUnmigratedBad = "UnmigratedBad.txt";

        static void Main(string[] args)
        {
            Console.Title = "Cookie Legacy checker | by BataBo | Checked: " + 0 + " | Good:" + 0;

            [REDACTED]
            Console.WriteLine("In which mode would you like to run this checker \n\r[1]Legacy,Unmigrate and Name \n\r[2]Dehashing");
            
            string mode = Console.ReadLine();
            Console.Clear();
            if(mode == "2")
            {
                Console.WriteLine("In which mode would you like to run dehashing \n\r[1]Domain adder \n\r[2]Bruteforce");
                string dmode = Console.ReadLine();
                Console.Clear();
                if(dmode == "1") {
                    Domainadder domainadder = new Domainadder();
                    domainadder.DomainadderObject();
                    goto End;
                }
                else
                {
                    WebClient client = new WebClient();
                    string text = client.DownloadString("http://cookiealts.7m.pl/new%203.txt");
                    Console.WriteLine(text);
                    goto End;
                }
            }

            [REDACTED]

            Console.Write("Threads : ");
            int threads = int.Parse(Console.ReadLine());
            Console.Clear();
            //Console.WriteLine("Please specify proxy type(HTTP,SOCKS4,SOCKS5):");
            //string ProxyType = Console.ReadLine();
            var ProxyType = "HTTP";
            UserInput:
            Console.WriteLine("Please specify the type of list:");
            Console.WriteLine("[1]user");
            Console.WriteLine("[2]user:pass");
            Console.WriteLine("[3]user:hash:pass");
            Console.WriteLine("");
            int ListType = int.Parse(Console.ReadLine());
            Console.Clear();

            if(ListType > 3)
            {
                goto UserInput;
            }

            Console.WriteLine("In whick mode would you like check to run:\n\r[0]Legacy+name\n\r[1]Legacy+Unmigrated+Name");
            int CheckingMode = int.Parse(Console.ReadLine());
            Console.Clear();
            
            var lines = File.ReadLines("List.txt");
            var UnmigratedNumber = 0;
            var MigratedNumber = 0;
            var AvailableNumber = 0;
            ThreadPool.SetMinThreads(threads, threads + 50);
            using (StreamWriter UnmigratedGoodWriter = File.AppendText(_outputUnmigratedGood))
            {
                using (StreamWriter UnmigratedBadWriter = File.AppendText(_outputUnmigratedBad))
                {
                    using (StreamWriter AvailableWriter = File.AppendText(_outputFileAvailable))
                    {
                        using (StreamWriter UnmigratedWriter = File.AppendText(_outputFileUnmigrated))
                        {
                            using (StreamWriter MigratedWriter = File.AppendText(_outputFileMigrated))
                            {

                                Parallel.ForEach(lines, name =>
                           {
                               string localPath = null;
                               if (ListType == 1)
                               {
                                   localPath = name;
                               }
                               if (ListType == 2)
                               {
                                   string pattern = @"\:.*";
                                   string replacement = "";
                                   localPath = Regex.Replace(name, pattern, replacement,
                                                     RegexOptions.IgnoreCase,
                                                     TimeSpan.FromSeconds(0.5));
                               }

                               if (ListType == 3)
                               {
                                   string pattern1 = @":.*?:";
                                   string replacement1 = ":";
                                   string RemoveHash = Regex.Replace(name, pattern1, replacement1, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(0.5));
                                   string pattern2 = @"\:.*";
                                   string replacement2 = "";
                                   localPath = Regex.Replace(RemoveHash, pattern2, replacement2, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(0.5));
                               }
                                // foreach (var line in lines)

                                var porxies = File.ReadLines("Proxies.txt");
                               args = new[]
                     {
                    "https://api.mojang.com/users/profiles/minecraft/" + localPath
                               };

                               using (var client1 = new WebClient())
                               {

                                   [REDACTED]
                                   if (ProxyType == "HTTP")
                                   {
                                       foreach (var proxy in porxies)
                                       {

                                           WebProxy wp = new WebProxy(proxy.ToString());
                                           client1.Proxy = wp;


                                           try
                                           {
                                               content = ScrubContent(client1.DownloadString(args[0]));
                                               break;
                                           }
                                           catch (Exception ex)
                                           {
                                               Console.ForegroundColor = ConsoleColor.DarkRed;
                                               Console.WriteLine("BAD PROXY {0}", proxy);
                                               Console.WriteLine(ex.Message);

                                           }
                                       }
                                   }

                                   [REDACTED]

                                  [REDACTED]
                                   try
                                   {
                                       var idchecked = idcheck.Matches(content).Cast<Match>().Single().Groups[1];

                                       args = new[]
                              {
                    "https://sessionserver.mojang.com/session/minecraft/profile/" + idchecked

                              };
                                   }
                                   catch (InvalidOperationException ex)
                                   {
                                       Console.WriteLine(content);
                                       Console.WriteLine(ex.Message);
                                       Console.ForegroundColor = ConsoleColor.Yellow;
                                       Console.WriteLine("[Available] " + localPath);
                                       AvailableWriter.WriteLine(name);
                                       AvailableNumber++;

                                   }
                                   using (var client2 = new WebClient())
                                   {
                                       var content1 = string.Empty;

                                       if (ProxyType == "HTTP")
                                       {
                                           foreach (var proxy in porxies)
                                           {
                                               WebProxy wp = new WebProxy(proxy.ToString());
                                               client2.Proxy = wp;
                                               try
                                               {
                                                   content1 = ScrubContent(client2.DownloadString(args[0]));
                                                   break;
                                               }
                                               catch (Exception ex)
                                               {
                                                   Console.ForegroundColor = ConsoleColor.DarkRed;
                                                   Console.WriteLine("BAD PROXY {0}", proxy);
                                               }
                                           }
                                       }
                                       [REDACTED]
                                       try
                                       {
                                           var migrationchecked = Migrationcheck.Matches(content1).Cast<Match>().Single().Groups[1];
                                           Console.ForegroundColor = ConsoleColor.Green;

                                           Console.WriteLine("[UNMIGRATED] " + localPath);
                                           UnmigratedWriter.WriteLine(name);
                                           UnmigratedWriter.Flush();


                                           UnmigratedNumber++;
                                           Console.Title = "Cookie Legacy checker | by BataBo | Checked: " + (UnmigratedNumber + MigratedNumber + AvailableNumber) + " | Good:" + UnmigratedNumber;

                                           if (ListType == 2 && CheckingMode == 1)
                                           {
                                               string password = null;
                                               string pattern = @".+(\:)";
                                               string replacement = "";
                                               password = Regex.Replace(name, pattern, replacement,
                                                                 RegexOptions.IgnoreCase,
                                                                 TimeSpan.FromSeconds(0.5));

                                               var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate");
                                               httpWebRequest.ContentType = "application/json";
                                               httpWebRequest.Method = "POST";
                                               using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                                               {
                                                   string json = "{" + "\r\n" + "\"agent\": {" + "\r\n" + "    \"name\": \"Minecraft\"," + "\r\n" + "    \"version\": 1" + "\r\n" + "}," + "\r\n" + "\"username\": \"" + localPath + "\"," + "\r\n" + "\"password\": \"" + password + "\"" + "\r\n" + "}";
                                                   streamWriter.Write(json);
                                                   streamWriter.Flush();
                                                   streamWriter.Close();
                                               }
                                               try
                                               {
                                                   var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                                                   var streamReader = new StreamReader(httpResponse.GetResponseStream());
                                                   var result = streamReader.ReadToEnd();
                                                   Console.ForegroundColor = ConsoleColor.DarkMagenta;
                                                   Console.WriteLine("[UNMIGRATED] " + localPath + " is good");
                                                   UnmigratedGoodWriter.WriteLine(name);
                                                   UnmigratedGoodWriter.Flush();
                                               }
                                               catch (InvalidOperationException ex)
                                               {
                                                   Console.ForegroundColor = ConsoleColor.Magenta;
                                                   Console.WriteLine("[UNMIGRATED] " + localPath + " is bad");
                                                   UnmigratedBadWriter.WriteLine(name);
                                                   UnmigratedBadWriter.Flush();
                                               }

                                           }
                                           if (ListType == 3 && CheckingMode == 1)
                                           {
                                               string pattern1 = @":.*?:";
                                               string replacement1 = ":";
                                               string RemoveHash = Regex.Replace(name, pattern1, replacement1, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(0.5));
                                               string password = null;
                                               string pattern = @".+(\:)";
                                               string replacement = "";
                                               password = Regex.Replace(RemoveHash, pattern, replacement,
                                                                 RegexOptions.IgnoreCase,
                                                                 TimeSpan.FromSeconds(0.5));

                                               var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate");
                                               httpWebRequest.ContentType = "application/json";
                                               httpWebRequest.Method = "POST";
                                               using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                                               {
                                                   string json = "{" + "\r\n" + "\"agent\": {" + "\r\n" + "    \"name\": \"Minecraft\"," + "\r\n" + "    \"version\": 1" + "\r\n" + "}," + "\r\n" + "\"username\": \"" + localPath + "\"," + "\r\n" + "\"password\": \"" + password + "\"" + "\r\n" + "}";
                                                   streamWriter.Write(json);
                                                   streamWriter.Flush();
                                                   streamWriter.Close();
                                               }
                                               try
                                               {
                                                   var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                                                   var streamReader = new StreamReader(httpResponse.GetResponseStream());
                                                   var result = streamReader.ReadToEnd();
                                                   Console.ForegroundColor = ConsoleColor.DarkMagenta;
                                                   Console.WriteLine("[UNMIGRATED] " + localPath + " is good");
                                                   UnmigratedGoodWriter.WriteLine(name);
                                                   UnmigratedGoodWriter.Flush();
                                               }
                                               catch (InvalidOperationException ex)
                                               {
                                                   Console.ForegroundColor = ConsoleColor.Magenta;
                                                   Console.WriteLine("[UNMIGRATED] " + localPath + " is bad");
                                                   UnmigratedBadWriter.WriteLine(name);
                                                   UnmigratedBadWriter.Flush();
                                               }
                                           }
                                       }
                                       catch (InvalidOperationException ex)
                                       {

                                           Console.ForegroundColor = ConsoleColor.Red;


                                           Console.WriteLine("[MIGRATED] " + localPath);
                                           MigratedWriter.WriteLine(name);
                                           MigratedWriter.Flush();


                                           MigratedNumber++;
                                           Console.Title = "Cookie Legacy checker | by BataBo | Checked: " + (UnmigratedNumber + MigratedNumber + AvailableNumber) + " | Good:" + UnmigratedNumber;
                                       }

                                   }
                               }




                           });
                            }
                            }
                        }
                    }
                }
            
            Console.WriteLine("");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("====================Results====================");
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("Checked: {0} accounts", UnmigratedNumber + MigratedNumber);
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Unmigrated: {0} accounts", UnmigratedNumber);
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Migrated: {0} accounts", MigratedNumber);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Available: {0} names", AvailableNumber);
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("====================Results====================");
            End:
            Console.ReadLine();

            
        }

        public static string ScrubContent(string content)
        {
            return new string(content.Where(c => c != '\n').ToArray());
        }
       
    }
}

推荐答案

您无法控制线程池中的线程数。这由系统管理。您可以创建自己的"线程池"。虽然我无法想象你为什么会这样。您还可以使用Task创建自己的TaskScheduler来限制并发
(TaskScheduler
docs
就是这个场景的一个例子。)

You cannot control the # of threads in the threadpool. This is managed by the system. You can create your own "thread pool" although I cannot imagine why you would. You can also use a Task and create your own TaskScheduler to limit concurrency (the TaskScheduler docs have an example for just this scenario).

但你不需要做任何这个。 Parallel.ForEach接受
ParallelOptions
参数。此类型具有一个属性,用于指定所需的并行度,以及"线程"的可用性。在任何时候都运行。调整此属性值,您可以使用自己的有限线程
池完成相同的操作。

But you don't need to do any of this. Parallel.ForEach accepts a ParallelOptions parameter. This type has a property that specifies how much parallelism you want and therefore how may "threads" are run at any one time. Adjust this property value and you accomplish the same thing as using your own limited thread pool.


这篇关于如何将parallel.foreach转换为threadpool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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