Reputation: 13
Hi I am trying to update my listbox asyncronously, so it wouldnt freeze for one sec while updating, unfortunately it throws an exception
My code
private async void timer1_Tick(object sender, EventArgs e) {
await Task.Run(() =>
{
listBox1.DataSource = listboxitems;
listBox1.TopIndex = listBox1.Items.Count - 1;
});
}
Exception
System.Reflection.TargetInvocationException:
InvalidOperationException: Invalid cross-thread operation: the listBox1 control was accessed by a different thread
than the thread for which it was created.
Anyone got a clue, how can I fix this ?
Upvotes: 0
Views: 301
Reputation: 888
Cross thread is when you try to invoke from another thread (in your case the Task one) a method of the main thread (in your case the UI one).
You can ask, from the secondary thread, that UI thread do the work like this:
listBox1.Dispatcher.Invoke(() => {
listBox1.DataSource = listboxitems;
listBox1.TopIndex = listBox1.Items.Count - 1;
});
Upvotes: 3