sooprise
sooprise

Reputation: 23177

Adding Items To A ListView From A Different Thread? (Cross-thread operation not valid)

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?

Upvotes: 0

Views: 9411

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456322

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.

Upvotes: 0

Sebastian Brózda
Sebastian Brózda

Reputation: 879

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)
    }
}

Upvotes: 3

Related Questions