1

I am beginner to C# .net. I have simple app in wpf which access a listbox from user thread. in winforms i can use invokerequired, a equivalent for wpf using dispatcher did not help. My system also hangs for the buttons so debugging is though. Please provide solution for the below code. thanks in advance

private void Monitor_mtd()
        {
                while (AppStatus != 0)
                {
                    if (flag2 == 1)
                    {
                        listBox1.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                            new list1MtdDelegate(list1Mtd), "Best practice");

                    }
               }
        }
        private delegate void list1MtdDelegate(string ls1);
        private void list1Mtd(string ls1)
        {
            listBox1.Items.Add(ls1);
        }


        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            Monitor = new Thread(new ThreadStart(Monitor_mtd));
            Monitor.Start();
            flag1 = 1;
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            flag2 = 1;
        }
Anu Shri
  • 11
  • 1

1 Answers1

0

There are a couple of issues that arise in your approach. Firstly, the way that you bind your data to the ListBox and secondly trying to update the ListBox from a user thread.

You can solve the binding of the ListBox by using an ObservableCollection so that the UI is updated with the necessary values (have a look at this post for more information on this). However, this also raises another problem and that is that the ObservableCollection cannot be called from another thread other than the one it is dispatching (see more on this here also). This means that you need another implementation for the ObservableCollection. Thomas Levesque made an AsyncObservableCollection that can be modified from any thread and still notify the UI when its modified.

I made a sample implementation that you can download here showing the full solution.

Community
  • 1
  • 1
pdvries
  • 1,372
  • 2
  • 9
  • 18