简体   繁体   English

C#-在parallel.foreach循环内写入文本文件

[英]C# - Writing to text file inside parallel.foreach loop

I made a proxy checker, however, since I usnig Parallel.foreach loop, I get after X amount of time, an error and the program just crash. 我做了一个代理检查器,但是,因为我使用了Parallel.foreach循环,所以我花了X倍的时间,看到一个错误,程序崩溃了。

it says that the writing is already used by another process, here is my code: 它说写作已经被另一个进程使用,这是我的代码:

public static void Check()
    {
        Proxy.Load();
        ThreadPool.SetMinThreads(Program.Threads, Program.Threads); // For example 100, 100
        ThreadPool.SetMaxThreads(Program.Threads, Program.Threads); // For example 100, 100
        Parallel.ForEach(Proxy.Proxies, proxy =>
        {
            using (var request = new HttpRequest())
            {
                try
                {
                    request.UserAgent =
                        "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.183 Safari/537.36 Viv/1.96.1147.52";
                    request.Proxy = HttpProxyClient.Parse(proxy);
                    request.ConnectTimeout = Program.TimeOut;
                    var Post = request.Post("http://209.250.244.126/judge/");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"[+] {proxy} - HTTP");
                    HTTP.Add(proxy);
                }
                catch
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"[-] {proxy}");
                }
            }
            // Write the Good proxies to the text file
            File.WriteAllLines(Environment.CurrentDirectory + "/Good.txt", HTTP);
        });
    }

What I need it to do: 我需要它做的是:

I want to write all the Good proxies to the text file while the check is running, and I still want to use threads to make the check much faster 我想在检查运行时将所有Good代理写入文本文件,并且我仍想使用线程使检查更快

Try wrapping the file output line in a lock statement . 尝试将文件输出行包装在lock语句中 This will restrict assess to the file to only one thread at a time. 这会将评估限制为一次只将文件限制为一个线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM