结合 backgroundworker 和多线程 C#

Combine backgroundworker and multitread C#

我有一个 C# 程序,它应该 运行 一个 C++ exe 文件,其中包含 .xlxs 文件形式的多个不同输入。它看起来像这样:

FormfrmRun 打开时,它会创建一个后台工作程序,然后调用 myWorker_DoWork

private List<RunSettings> inputfiles = new List<RunSettings>(); //this is just a struct with getter and setters for all of the values that the constructor for frmRun takes

public frmRun(bool SaveCsvFiles, bool DeleteCsvFiles, bool OpenOutputFile, string[] files) //this is called from a main form in the real program
{
    InitializeComponent();
    Show();
    Refresh();
    foreach (string file in files) //for each one of the files in the list
    {
        inputfiles.Add(new RunSettings(file, SaveCsvFiles, DeleteCsvFiles, OpenOutputFile));
    }

    //https://www.codeproject.com/Articles/841751/MultiThreading-Using-a-Background-Worker-Csharp
    //here is the background handler stuff
    myWorker.DoWork += new DoWorkEventHandler(myWorker_DoWork); //Event handler, which will be called when the background worker is instructed to begin its asynchronous work. It is here inside this event where we do our lengthy operations, for example, call a remote server, query a database, process a file... This event is calle
    myWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(myWorker_RunWorkerCompleted); //Event handler, which occurs when the background worker has finished execution has been canceled or has raised an exception.This event is called on the main thread, which means that we can access the user controls from inside this method.
    myWorker.ProgressChanged += new ProgressChangedEventHandler(myWorker_ProgressChanged); //Event handler which occurs when the ReportProgress method of the background worker has been called. We use this method to write the progress to the user interface. This event is called on the main thread, which means that we can access the user controls from inside this method.
    myWorker.WorkerReportsProgress = true; //Needed to instruct the worker that it can report progress to the main thread.
    myWorker.WorkerSupportsCancellation = true; //Needed to instruct the worker that it can be canceled upon the user request.
    myWorker.RunWorkerAsync(files);//Call the background worker
}

myWorker_DoWork 然后我想处理 inputfiles List:

中每个文件所需的所有操作
protected void myWorker_DoWork(object sender, DoWorkEventArgs e) //starting the program for a list of files
{
    BackgroundWorker sendingWorker = (BackgroundWorker)sender;//Capture the BackgroundWorker that fired the event
    var tasks = new List<Task>();

    for (int i = 0; i < inputfiles.Count; i++) //for each one of the files in the list
    {
        if (!sendingWorker.CancellationPending) //At each iteration of the loop, check if there is a cancellation request pending 
        {
            sendingWorker.ReportProgress(0, "Starting the Program for " + Path.GetFileNameWithoutExtension(inputfiles[i].filename));
            RunMyProgram RunAndSummarize = new RunMyProgram ();
            RunAndSummarize.Progress += ProgressUpdate; //
            var task = Task.Run(() => RunAndSummarize.Run(inputfiles[i]));
            tasks.Add(task);

            //RunAndSummarize.Run(inputfiles[i]);
        }
        else
        {
            e.Cancel = true;//If a cancellation request is pending, assign this flag a value of true
            break;// If a cancellation request is pending, break to exit the loop

            //this needs to be reworked a bit if we are gonna use it... We have to call it somewhere and stuff
        }
    }

    Task.WaitAll(tasks.ToArray());

    Close();
}

在我的 RunProgram Class 中,除了将 .xlsx 文件转换为 csv 文件外,我现在没有做太多事情:

public void Run(RunSettings settings)
{ 
    ExcelFile InputFile = new ExcelFile(); //a class that handels the Excel related stuff in the program
    string fileNameWithoutExt = Path.GetFileNameWithoutExtension(settings.filename);
    string DirectoryofInputFile = Path.GetDirectoryName(settings.filename);
    string DirectoryofOutputFile = DirectoryofInputFile + @"\" + fileNameWithoutExt;

    //the output file is be created in a subfolder with the same name as the input file
    OutputFolder MakeOutputFolderAndCopyInputFile = new OutputFolder();
    MakeOutputFolderAndCopyInputFile.MakeOuputDirectory(DirectoryofOutputFile); //created in the same folder as the input
    MakeOutputFolderAndCopyInputFile.CopyInputFile(settings.filename, DirectoryofOutputFile, " output");

    //saves the excel file to csv
    Progress(0, "Converting the inputfile for " + fileNameWithoutExt + "..."); //
    InputFile.OpenExcel(DirectoryofInputFile, fileNameWithoutExt + ".xlsx");
    InputFile.SetActiveSheet(0);
    InputFile.SaveAsCsv(DirectoryofOutputFile, fileNameWithoutExt);
    InputFile.Close();
    InputFile = null;
}

我的问题是,当我尝试像上面那样使用 multi treading 时,出现如下错误:

system argument out of range exception: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index.

当我删除 myWorker_DoWork 中的多线程内容并且只是一个一个地转换文件或者当我只是跳过 background worker 并为用户隐藏进度时,代码工作得很好.你知道我做错了什么吗?我不能在 C# 中组合 background workermulti thread 吗?

编辑:进度更新class。

protected void ProgressUpdate(int progress, string text) //tells the user what is happening
{
    base.Invoke((Action)delegate
    {
        string time = DateTime.Now.ToString("HH:mm:ss");

        lblStatus.Text = text + "...";

        string newstatustext = time + ": " + text;
        if (txtProgress.Lines.Length > 0) //dont add a new line for the first line in the textbox, otherwise do
        {
            newstatustext = Environment.NewLine + newstatustext;
        }
        txtProgress.Text += newstatustext;

        txtProgress.Refresh();
        prgProgress.Value += progress / inputfiles.Count; //we give the status for one file but we want the precentage for all of the files
        prgProgress.Refresh();
    });
}

您的代码的问题是您在 Task.Run 中使用了 i,但是当 Task.Run 中的代码执行时,循环已经完成并且i 的值已更改。

通过使用变量 j 捕获 i,您可以避免这个问题。

for (int i = 0; i < inputfiles.Count; i++) //for each one of the files in the list
{
    if (!sendingWorker.CancellationPending) //At each iteration of the loop, check if there is a cancellation request pending 
    {
        sendingWorker.ReportProgress(0, "Starting the Program for " + Path.GetFileNameWithoutExtension(inputfiles[i].filename));
        RunMyProgram RunAndSummarize = new RunMyProgram();
        RunAndSummarize.Progress += ProgressUpdate; //
        var j = i;
        var task = Task.Run(() => RunAndSummarize.Run(inputfiles[j]));
        tasks.Add(task);

        //RunAndSummarize.Run(inputfiles[i]);
    }
    else
    {
        e.Cancel = true;//If a cancellation request is pending, assign this flag a value of true
        break;// If a cancellation request is pending, break to exit the loop

        //this needs to be reworked a bit if we are gonna use it... We have to call it somewhere and stuff
    }
}