-1

in wpf,I have a listbox control and two buttons.I want to be able to use the second button when i clicked the first button till add numbers has not fineshed his work.I use dispatcher.begininvoke but this adds the work on main thread.How to i synchronize this threads?I want to be able to use second button, move the window or using other ui elements when addnumbers processing..

    void AddNumbers()
    {

                for (int i = 1; i <= 1000000; i++)
                {
                    listBox1.Items.Add(i);
                }

    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {

        Thread thr = new Thread(new ThreadStart(AddNumbers));
        thr.Start();


    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {

        MessageBox.Show("Hello World!");
    }
4

1 回答 1

0

只有主 (UI) 线程可以访问 UI 控件。为什么列表框中需要 100 万个项目?Listbox 支持虚拟化。使用 BackgroundWorker(或线程)创建 List,然后在 RunWorkerCompleted 上将 List 绑定到 UI ListBox。至于同步,您只需在启动 BackgroundWorker 时启用/禁用,然后在回调中启用/禁用。同样,为什么您需要在 ListBox 中包含 100 万个项目?

http://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx

于 2012-06-22T23:49:51.033 回答