1

a 构建一个应用程序来获取视频文件(avi、mpeg..)并转换为另一种格式。

我的应用程序有我添加文件的列表框,我添加了添加目录的选项,所以使用SafeFileEnumerator类(我在这里找到它)我检查目录根并只收到具有权限的文件夹,当然还有所有文件,而不是我想要添加所有相关文件都放入我的列表框中,但如果线程为了避免 mt GUI 冻结,我想这样做,所以我尝试使用 BackgroundWorker,我认为我需要一些帮助来完成它,因为在我的情况下它不起作用适当地:

private void btnAddDirettory_Click_1(object sender, EventArgs e)
{
    string fileToAdd = string.Empty;
    BackgroundWorker backgroundWorker = null;
    DialogResult dialog = folderBrowserDialog1.ShowDialog();
    if (dialog == DialogResult.OK)
    {
        btnAddfiles.Enabled = false;
        btnAddDir.Enabled = false;
        btnPlay.Enabled = false;
        someClass myClass= new someClass ();

        foreach (string fileName in SafeFileEnumerator.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories))
        {
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.DoWork +=
            (s1, e1) =>
            {
                if (myClass.iAviFormat(fileName))
                {
                    if (myClass.isCorrectFormat(fileName))
                    {
                        backgroundWorker.ReportProgress(0, fileName);
                        //listBoxFiles.Items.Add(fileName);
                    }
                    else if (!myClass.isCorrectFormat(fileName))
                    {
                        fileToAdd = myClass.getNewFileName(fileName);
                        backgroundWorker.ReportProgress(0, fileToAdd);
                    }
                }
            };
        }

        backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        (s1, e1) =>
        {
            btnPlay.Enabled = true;
            btnClear.Enabled = true;
            btnAddfiles.Enabled = true;
            btnAddDir.Enabled = true;
        });

        backgroundWorker.ProgressChanged +=
         (s1, arguments) =>
         {
             listBoxFiles.Items.Add(arguments.UserState);
         };

        backgroundWorker.RunWorkerAsync();
    }
}
4

1 回答 1

2

我认为您应该将 foreach 移至后台工作人员 DoWork 中。

就像是

backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork +=
(s1, e1) =>
{
    string fileToAdd = string.Empty;
    someClass myClass= new someClass ();

    foreach (string fileName in SafeFileEnumerator.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories))
    {
        if (myClass.iAviFormat(fileName))
        {
            if (myClass.isCorrectFormat(fileName))
            {
                backgroundWorker.ReportProgress(0, fileName);
                //listBoxFiles.Items.Add(fileName);
            }
            else if (!myClass.isCorrectFormat(fileName))
            {
                fileToAdd = myClass.getNewFileName(fileName);
                backgroundWorker.ReportProgress(0, fileToAdd);
            }
        }
    }
};
于 2012-12-21T08:14:58.280 回答