多线程应用程序中的数据访问

时间:2011-04-24 19:05:39

标签: c# .net multithreading

我正在使用以下代码运行多个线程来处理一些耗时的任务:

  public void RunWhileRemainThreads()
    {
        string[] options = new string[2];
        int i = 0;

        while (LeftToRun > 0)
        {
            if (CurrentRunningThreads < MaxThreadsRunning)
            {
                options[0] = list_test[i];
                options[1] = bla;

                BackgroundWorker myThread = new BackgroundWorker();
                myThread.DoWork += new DoWorkEventHandler(backgroundWorkerRemoteProcess_DoWork);
                myThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorkerRemoteProcess_RunWorkerCompleted);
                myThread.ProgressChanged += new ProgressChangedEventHandler(backgroundWorkerRemoteProcess_ProgressChanged);
                myThread.WorkerReportsProgress = true;
                myThread.WorkerSupportsCancellation = true;

                myThread.RunWorkerAsync(options);

                Thread.Sleep(3000);
                CurrentRunningThreads++;
                i++;
                LeftToRun--;
            }
        }
    }

        private void backgroundWorkerRemoteProcess_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] options = (string[])e.Argument;
            string option1 = options[0];
            string option2 = options[1];

            RemoteProcess myRemoteProcess = new RemoteProcess(option1, option2);
            myRemoteProcess.FalseExec();
        }

我的问题是,当我在没有Thread.Sleep(3000)的情况下运行时,option1变量是相同的! (我在RemoteProcess.FalseExec())内打印。

我想我应该以不同的方式管理这个参数,但我找不到。

1 个答案:

答案 0 :(得分:0)

您只需要停止在所有后台工作人员之间共享相同的数组:

public void RunWhileRemainThreads()
{
    int i = 0;

    while (LeftToRun > 0)
    {
        if (CurrentRunningThreads < MaxThreadsRunning)
        {
            options[0] = ;
            options[1] = bla;

            BackgroundWorker myThread = new BackgroundWorker();
            myThread.DoWork += new DoWorkEventHandler(backgroundWorkerRemoteProcess_DoWork);
            myThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorkerRemoteProcess_RunWorkerCompleted);
            myThread.ProgressChanged += new ProgressChangedEventHandler(backgroundWorkerRemoteProcess_ProgressChanged);
            myThread.WorkerReportsProgress = true;
            myThread.WorkerSupportsCancellation = true;

            // THIS IS THE IMPORTANT CHANGE
            myThread.RunWorkerAsync(new string[2] { list_test[i], bla });

            CurrentRunningThreads++;
            i++;
            LeftToRun--;
        }
    }
}

这样每个BackgroundWorker都会收到一个不同的string[]作为参数,因此两个工作人员不可能获得相同的值。