I am facing to a very strange issue when I use dispatcher.invoke method in wpf.
Background:
I defined a user control there is a DoWorkEventArgs to support some async work:
public class MyUserControl : UserControl
{
private BackgroundWorker bw;
public MyUserControl()
{
bw.DoWork += new DoWorkEventHandler(DoWorkMethod);
}
public void StartWork()
{
bw.RunWorkerAsync();
}
void DoWorkMethod(object sender, DoWorkEventArgs e)
{
this.Dispatcher.Invoke((System.Action)delegate()
{
//Add some item in a ListBox, this ListBox is defined in the user control.
TextBlock b = new TextBlock();
//some code
Listbox.Items.Add(b);
}
}
}
When a button click I created 2 instance of this user control and call there StartWork method:
MyUserControl control1 = new MyUserControl();
MyUserControl control2 = new MyUserControl();
control1.StartWork();
control2.StartWork();
Here is the problem, sometimes the ListBox in usercontrol1 is not updated, there is no item in it, sometimes this situation happend in the ListBox of usercontrol2, I debug them and I found the code runs normal, the ListBox.Items.Add method runs, and the results just don't come out. If I change Dispatcher.Invoie to Dispatcher.BeginInvoke, then it's normal. Is anyone know the reason?