John
John

Reputation: 13

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.

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

Upvotes: 1

Views: 2627

Answers (1)

D Jordan
D Jordan

Reputation: 84

Try wrapping the file output line in a lock statement. This will restrict assess to the file to only one thread at a time.

Upvotes: 0

Related Questions