是否可以从BackgroundWorker ProgressChanged中访问ListView项?

本文关键字:访问 ListView ProgressChanged BackgroundWorker 是否 | 更新日期: 2023-09-27 18:12:21

我有一个UI被BackgroundWorker ProgressChanged更新。它有一个进度条,和一个列表视图,显示每个项目的文件名由后台工作者。

我只想在listview中添加一个项目,如果它是一个新文件,所以我试图在listview中使用最后一个项目和当前文件名之间的比较。

然而,这会抛出一个TargetInvocation错误。

void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        var r = Enumerable.Empty<ListViewItem>();
        if (this.listView1.Items.Count > 0)
            r = this.listView1.Items.OfType<ListViewItem>();
        var last = r.LastOrDefault();
        if (last.Text != CurrentTrack.Name)
        {
            ListViewItem LVI = new ListViewItem(currentTrack.Name);
            LVI.SubItems.Add(keywords);
            LVI.SubItems.Add("Updated");
            listView1.Items.Add(LVI);
            listView1.TopItem = LVI;
            listView1.EnsureVisible(listView1.Items.Count - 1);
        }

        progressBar1.Value = e.ProgressPercentage;
        lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
    }

这有可能实现吗?

是否可以从BackgroundWorker ProgressChanged中访问ListView项?

您需要在UI线程上执行UI更改。这可以使用以下代码实现:

frmMain()
{
    Worker_ProgressChanged = new Worker_ProgressChanged_Delegate(m_oWorker_ProgressChanged);
}
delegate void Worker_ProgressChanged_Delegate(object sender, ProgressChangedEventArgs e);
Worker_ProgressChanged_Delegate Worker_ProcessChanged;
void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (this.InvokeRequired)
    {
        this.Invoke(Worker_ProgressChanged, sender, e);
    }
    else
    {
        ... Add list items etc.
    }

如果工作线程调用了这个方法,invokerrequired将为true。然后,表单将使用它的线程(UI线程)调用相同的方法。这次invokerequirequired为false,函数在正确的线程上执行。

Edit:根据注释将add列表项移动到else块

会抛出相同的错误吗?

    void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        ListViewItem last = null;
        if (this.listView1.Items.Count > 0)
        {
            last = this.listView1.Items[listView1.Items.Count - 1];
        }
        if (last == null || last.Text != CurrentTrack.Name)
        {
            ListViewItem LVI = new ListViewItem(currentTrack.Name);
            LVI.SubItems.Add(keywords);
            LVI.SubItems.Add("Updated");
            listView1.Items.Add(LVI);
            listView1.TopItem = LVI;
            listView1.EnsureVisible(listView1.Items.Count - 1);
        }
        progressBar1.Value = e.ProgressPercentage;
        lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
    }