C# – Making a cross-thread call to a ListView

cdelegateslistviewmultithreading

I have a thread running in the background that periodically tries to update a ListView component, but every time it attempts to I get a "Cross-thread operation not valid: Control 'dlList' accessed from a thread other than the thread it was created on." error. I have used a delegate to try and solve this but it isn't fixing the problem. Is there something wrong with my code? I've also tried Invoke instead of BeginInvoke but same issue.

    delegate void updateListItemDelegate(string tag, ListViewItem lv);
    private void updateListItem(string tag, ListViewItem lv)
    {
        if (this.dlList.InvokeRequired)
        {
            this.dlList.BeginInvoke(new updateListItemDelegate(updateListItem),tag,lv);
            return;
        }
        else
        {
            int index = -1;
            foreach (ListViewItem x in dlList.Items)
            {
                if (x.Tag.ToString() == tag)
                    index = x.Index;
            }
            if (index != -1)
            {
                dlList.Items[index].SubItems[1] = lv.SubItems[1];
                dlList.Items[index].SubItems[3] = lv.SubItems[3];
            }
        }
    }

Called via:

    updateListItem(x.url, x.details);

Best Answer

Try the AsyncObservableCollection from Thomas Levesque.