views:

244

answers:

2

Hi,

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);
A: 

Try the AsyncObservableCollection from Thomas Levesque.

Guge
A: 

Ah. I had a try {} catch {} around the code logging the exception, didn't realise that a ListView item I had set in a class also required a delegate to make a call to it as well as the form component. Nice tip Fredrik!

James
remember to accept the answer when you've got one.
Jason D