0

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 ?

  • Does this answer your question? [How to update a list box by an asynchronous call?](https://stackoverflow.com/questions/10004613/how-to-update-a-list-box-by-an-asynchronous-call) – default locale Jun 10 '21 at 11:45
  • 1
    Are you doing anything else inside the `await Task.Run` beyond updating the `listBox1`, that you have removed here for simplicity? – Theodor Zoulias Jun 10 '21 at 11:46
  • Use a Task / Thread only to collect the data, then `BeginInvoke()` a delegate in the UI Thread, or use a standard `IProgress` delegate, where you call `ListBox.BeginUpdate();`, set the data using the DataSource Property or the `Items.AddRange()` method, then `ListBox.EndUpdate();` – Jimi Jun 10 '21 at 14:14
  • Jimi - do you have an example of this (for AddRange)? I'm actually stuck with the same problem but with a listview and the answers here are incomplete and there's no datasource property for winforms listviews (probably because it requires items and subitems) – MC9000 Mar 04 '22 at 22:14

1 Answers1

3

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

                       
Emanuele
  • 723
  • 4
  • 15