0

我想将选项添加到我的应用程序中,以将包含目录中所有文件的目录添加到我的目录中ListView,因为我在添加到我之前检查每个文件ListView(我的文件是 Wiresahrk 文件,所以我正在检查文件扩展名,如果不是 pcap 格式,我转换文件然后添加),我想用单独的线程来做,所以我正在使用BackgroundWorker,我需要一些关于如何做的帮助:

private void btnAddDir_Click(object sender, EventArgs e)
{
    ListViewItem lv = new ListViewItem();
    string fileToAdd = string.Empty;
    List<string> filesList = new List<string>();
    BackgroundWorker backgroundWorker = null;
    DialogResult dialog = folderBrowserDialog1.ShowDialog();
    if (dialog == DialogResult.OK)
    {
        Editcap editcap = new Editcap();

        foreach (string file in SafeFileEnumerator.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories))
        {
            if (editcap.isWiresharkFormat(file))
            {
                filesList.Add(file);
            }
        }

        backgroundWorker = new BackgroundWorker();
        backgroundWorker.WorkerReportsProgress = true;
        backgroundWorker.DoWork +=
            (s1, e1) =>
            {
                foreach (string fileName in filesList)
                {
                    if (editcap.isWiresharkFormat(fileName))
                    {
                        if (editcap.isLibpcapFormat(fileName))
                        {
                            lv.Text = fileName;
                            lv.SubItems.Add(fileName);
                            lv.SubItems.Add("Waiting");

                            this.Invoke((MethodInvoker)delegate
                            {
                                lvFiles.Items.Add(lv);
                            });

                            lvFiles.Refresh();
                        }
                    }
                }
            };

        backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        (s1, e1) =>
        {

        });

        backgroundWorker.RunWorkerAsync();
    }
}
4

1 回答 1

1

backgroundWorker.ProgressChanged不要在事件中添加项目,而是在DoWork.

否则会报错Cross-thread operation not valid: Control ___ accessed from a thread other than the thread it was created on.

改变

backgroundWorker.ReportProgress(0, fileToAdd);

lv.SubItems.Add(fileToAdd);

此外,您不需要处理ProgressChangedRunWorkerCompleted事件。

于 2012-12-25T11:45:51.260 回答