构建一个接收视频文件(avi,mpeg ..)并转换为其他格式的应用程序。
我的应用程序有我添加文件的列表框,我添加了添加目录的选项,所以SafeFileEnumerator
类(我在这里找到)我检查目录root并只收到有权限的文件夹,当然所有文件,而不是我想将所有相关文件添加到我的列表框中,但我想这样做,如果线程,以避免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();
}
}
答案 0 :(得分: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);
}
}
}
};