Search code examples
c#multithreadinglistviewcompact-frameworkmobile

A problem in c# using Threads and ListView


I have a text filter where in the TextChanged event I launch a listview populate code this way:

ThreadPool.QueueUserWorkItem(new WaitCallback(populate));

Then in the populate method I have code like this

listView1.BeginUpdate();
listView1.Clear();

// rest of the code

listView1.EndUpdate();

but the listView1.BeginUpdate() call gives the following exception:

System.NotSupportedException was unhandled
  Message="An error message cannot be displayed because an optional resource assembly containing it cannot be found"
  StackTrace:
    at Microsoft.AGL.Common.MISC.HandleAr()
    at System.Windows.Forms.ListView.ntvSetStyleEx()
    at System.Windows.Forms.ListView.BeginUpdate()
    at App.frmSelectClient.populate()
    at WorkItem.doWork()
    at System.Threading.Timer.ring()
  InnerException: 

What I am doing wrong?

I would like to issue the populate of the ListView in a background thread.


Solution

  • You can't update UI elements from any thread other than the UI thread. Use Control.Invoke/BeginInvoke to do this.

    You can do all your data loading etc in the background thread, but you'll need to marshal to the UI thread to actually populate the UI controls themselves.

    This is the case in most UI frameworks - and certainly Windows Forms (desktop and CF) and Windows Presentation Foundation (where you use a Dispatcher rather than Control.Invoke/BeginInvoke).

    One point to note: if I remember rightly, the Compact Framework only supports the EventHandler delegate for Control.Invoke/BeginInvoke. That may have changed in more recent versions, admittedly.