views:

26

answers:

2

I'm trying to add items to a list view in a different thread than it was created in and am getting a cross-thread error. How can I make this element accessible in other threads?

+1  A: 

try to use property control: InvokeRequired - http://msdn.microsoft.com/en-us/library/ms171728%28VS.80%29.aspx

private delegate void AddItemCallback(object o);

private void AddItem(object o)
{
    if (this.listView.InvokeRequired)
    {
        AddItemCallback d = new AddItemCallback(AddItem);
        this.Invoke(d, new object[] { o });
    }
    else
    {
        // code that adds item to listView (in this case $o)
    }
}
Sebastian Brózda
Do I add this code where my listview is created or where I want to add to my listview?
Soo
A: 

Use a Task that does the update, scheduled to the UI using TaskScheduler.FromCurrentSynchronizationContext.

http://msdn.microsoft.com/en-us/library/dd997394.aspx

The advantage to this approach over Control.Invoke is that it will work in WPF, Silverlight, or Windows Forms, whereas Control.Invoke is Windows Forms-only.

P.S. If you're not on .NET 4.0 yet, then Task and TaskScheduler are available in the Rx library.

Stephen Cleary