直到BackgroundWorker的完成所有通话

直到BackgroundWorker的完成所有通话

本文介绍了如何等待,直到BackgroundWorker的完成所有通话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

添加按钮点击事件如何添加文件:

private void btnAddfiles_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        foreach (String file in openFileDialog1.FileNames)
        {
            System.IO.Stream stream;
            try
            {
                if ((stream = openFileDialog1.OpenFile()) != null)
                {
                    using (stream)
                    {
                        StartBackgroundFileChecker(file);
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
    }
}



每那我是传递给 StartBackgroundFileChecker文件(字符串文件)需要打开过程之前检查这个文件添加到我的的ListBox 所以我通过的BackgroundWorker 为了防止我的GUI冻结这样做的,所有的工作完美的:

every file that i am pass to StartBackgroundFileChecker(string file) need to open process and check this file before add to my ListBox so i am doing this via BackgroundWorker in order to prevent my GUi to freeze and all work perfect:

private void StartBackgroundFileChecker(string file)
{
    ListboxFile listboxFile = new ListboxFile();
    listboxFile.OnFileAddEvent += listboxFile_OnFileAddEvent;
    BackgroundWorker backgroundWorker = new BackgroundWorker();
    backgroundWorker.WorkerReportsProgress = true;
    backgroundWorker.DoWork +=
    (s3, e3) =>
    {
        //check my file via another class
    };

    backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
    (s3, e3) =>
    {
        ///
    });

    backgroundWorker.RunWorkerAsync();
}



当我完成阅读我的文件,我想更新我的UI等等如果我把里面的 backgroundWorker.RunWorkerCompleted ... 此UI更新它每次调用此函数后更新我的UI和我期待的方式在所有的结尾做电话

when i am finish to read all my files i want to update my UI so if i put this Ui update inside backgroundWorker.RunWorkerCompleted... it update my UI after every call to this function and i am looking for way to do it at the end of all calls

推荐答案

最简单的方法是保持一个计数器。

Most easy way is to keep a counter.

private int numWorkers = 0;



然后当你开始每个后台工作增加它。

Then increment it as you start each background worker.

using (stream)
{
    Interlocked.Increment(ref numWorkers);
    StartBackgroundFileChecker(file);
}



指定的的方法作为事件完成了对每台背景。工人

Assign Same method as event completed to each background worker.

backgroundWorker.RunWorkerCompleted += myCommonCompletedHandler;

在完成事件

递减计数器。

Decrement counter in completed event.

public void myCommonCompletedHandler(object sender, RunWorkerCompletedEventArgs e)
{
    if(Interlocked.Decrement(ref numWorkers) == 0)
    {
      // all complete
    }
}

这篇关于如何等待,直到BackgroundWorker的完成所有通话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:40