0

我对 Parallel.ForEach 感到很困惑。
请你帮我用 Parallel.ForEach 重写下面的代码:

    #region Register

    private void btnStartRegister_Click(object sender, EventArgs e)
    {
        if (backgroundWorker2.IsBusy)
        {
            btnStartRegister.Enabled = false;
            lblStatusOfaccMValue.Text = "Canceling...";
            backgroundWorker2.CancelAsync();
        }
        else
        {
            txtLogInRegister.Text = string.Empty;
            btnStartRegister.Text = "Cancel";
            lblUserCreatedCountValue.Text = "---";
            lblStatusOfaccMValue.Text = "Running...";

            backgroundWorker2.RunWorkerAsync();
        }
    }

    private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
    {
        backgroundWorker2.ReportProgress(Convert.ToInt32(0));

        int UsersCount = int.Parse(txtUsersCount.Text);
        UsersCreatedCount_Step = 0;
        string path = Application.StartupPath;
        string accfilePath = path + @"\acc.txt";
        string logfilePath = path + @"\log.txt";
        string Ok_ip_port = string.Empty;
        string[] Separator = new string[] { "__" };
        int list_lines_acc_Current = -1;

        string[] lines_acc = File.ReadAllLines(accfilePath);
        List<string> list_lines_acc = new List<string>(lines_acc);
        List<string> list_lines_acc_new = new List<string>(list_lines_acc);

        foreach (string line_acc in list_lines_acc)
        {
            if (backgroundWorker2.CancellationPending)
            {
                e.Cancel = true;
                break;
            }

            list_lines_acc_Current++;
            string[] line_acc_ar = line_acc.Split(Separator, StringSplitOptions.None);
            if (line_acc_ar.Length == 3)
            {
                string username = line_acc_ar[0];
                string password = line_acc_ar[1];
                string email = line_acc_ar[2];
                string[] email_ar = email.Split('@');
                email = email_ar[0] + "%40" + email_ar[1];


                list_lines_acc_new[list_lines_acc_Current] += "__" + txtSuffixURL.Text + "__" + txtServerNumber.Text + "__" + "127.0.0.1:2222";

                try
                {
                    bool[] RegisterMethod_res = RegisterMethod(bla bla bla);
                    bool failed = RegisterMethod_res[0];
                    bool world_full = RegisterMethod_res[1];
                    if (!failed)
                    {
                        UsersCreatedCount_Step++;
                        backgroundWorker2.ReportProgress(Convert.ToInt32(UsersCreatedCount_Step * (100.0 / UsersCount)));
                        list_lines_acc_new[list_lines_acc_Current] += "__" + "Y";
                    }
                    else
                    {
                        if (world_full)
                        {
                            list_lines_acc_new[list_lines_acc_Current] += "__" + "N";
                            e.Cancel = true;
                            break;
                        }
                        else
                        {
                            list_lines_acc_new[list_lines_acc_Current] += "__" + "N";
                        }
                    }

                    File.WriteAllLines(accfilePath, list_lines_acc_new.ToArray());
                }
                catch (Exception ex)
                {
                    list_lines_acc_new[list_lines_acc_Current] += "__" + "N";

                    File.WriteAllLines(accfilePath, list_lines_acc_new.ToArray());
                }

                if (UsersCount == UsersCreatedCount_Step)
                {
                    break;
                }
            }
        }

        File.WriteAllLines(accfilePath, list_lines_acc_new.ToArray());
    }

    private bool[] RegisterMethod()
    {
        bla bla bla
        ...
        ...
        return RegisterMethod_res;
    }

    private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar2.Value = e.ProgressPercentage;
        lblUserCreatedCountValue.Text = UsersCreatedCount_Step.ToString();
    }

    private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        btnStartRegister.Text = "Start Register";
        btnStartRegister.Enabled = true;

        if (e.Error != null)
        {
            MessageBox.Show(e.Error.Message);
            return;
        }
        if (e.Cancelled)
        {
            lblStatusOfaccMValue.Text = "Cancelled...";
        }
        else
        {
            lblStatusOfaccMValue.Text = "Completed";
        }
    }

    #endregion

我想foreach (string line_acc in list_lines_acc)Parallel.ForEach.
我不能这样做...
正如您所见,有一个用于写入的 acc 文件 ( acc.txt ) 和一些用于读取和写入的列表 ( list_lines_acc + list_lines_acc_new )。
它们在并行模式下总是存在问题。
编辑:
问题是关于这些行->

        if (UsersCount == UsersCreatedCount_Step)
        {
            break;
        }

我想在那种情况下停止它。
但我不知道UsersCreatedCount_Step在并行模式下如何工作?

非常感谢您的帮助。

提前致谢

4

1 回答 1

4

我不确定它是否可以安全地完成。这里有很多问题,包括您试图从多个线程写入同一个文件的事实:

File.WriteAllLines(accfilePath, list_lines_acc_new.ToArray());

该部分不仅需要锁,而且如果您有机械磁盘,还会降低性能。

于 2012-09-25T11:48:13.790 回答