c# - 如何使用 foreach 循环制作多线程应用程序

标签 c# multithreading

有一个应用程序可以根据某些条件对大型 txt 文件进行排序。 例如,我需要启动 5 个线程,但我使用 foreach 循环从文件中逐行读取。 如果我用我的代码启动 5 个线程,所有线程都将使用相同的行。

这是我启动 1 个线程的代码:

    Thread[] thr;
    private void button1_Click(object sender, EventArgs e)
    {
        button1.Enabled = false;
        button4.Enabled = true;
        decimal value = 1;
        int i = 0;
        int j = (int)(value);
        thr = new Thread[j];
        for (; i < j; i++)
        {
            thr[i] = new Thread(new ThreadStart(go));
            thr[i].IsBackground = true;
            thr[i].Start();
        }
    }

    private static IEnumerable<string> ReadLineFromFile(TextReader fileReader)
    {
        using (fileReader)
        {
            string currentLine;
            while ((currentLine = fileReader.ReadLine()) != null)
            {
                yield return currentLine;
            }
        }
    }


    public void go()
    {
        while (true)
        {
            TextReader readFile = new StreamReader(file_path, System.Text.Encoding.UTF8, true);
            foreach (string line in ReadLineFromFile(readFile))
            {
                if (line.Split(':')[0].Contains("@"))
                {
                    string out_line = line.Split(':')[0].Replace("+", "") + ":" + line.Split(':')[1];
                    lock (locker)
                    {
                        mail_count++;
                        log_mail(mail_count);
                        mail.Add(out_line.Trim().Replace(";", ":"));
                    }
                }
                else
                {
                    string out_line = line.Split(':')[0].Replace("+", "") + ":" + line.Split(':')[1];
                    lock (locker)
                    {
                        rubbish_count++;
                        log_rubbish(rubbish_count);
                        rubbish.Add(out_line.Trim());
                    }
                }
            }
            MessageBox.Show("Ready");
            BeginInvoke(
            new MethodInvoker(() =>
            {
                button1.Enabled = true;
                button4.Enabled = false;
            }));
            break;
        }
    }

最佳答案

所有线程都读取同一个文件是没有用的,并且从共享文件读取是困难且低效的。

在你的主要功能中,你需要这样的东西:

Parallel.ForEach(System.IO.File.ReadLines(file_path, System.Text.Encoding.UTF8), 
   line => ProcessOneLine(line) 
);

然后 ProcessOneLine 将执行 .Split(':')

关于c# - 如何使用 foreach 循环制作多线程应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16936568/

相关文章:

multithreading - 消息后 LParam 截断

c# - C# Parallel.ForEach 的工作何时完成?

java - 如何使用java并行流代替executorThreadsPool?

c# - 在 Windows Phone 异步服务中捕获服务器端异常

c# - 如何更改 Telerik OpenAccess 命名空间?

c# - 在 IE7 中启用 C# 清除 cookie

c# - 为什么 EF7/Core 插入重复记录?

java - 多线程的情况

java - 如何知道两个线程中哪个线程先完成执行

javascript - AngularJs 将查询字符串发布到 C# Controller