如何在WPF中操纵其他线程的模态对话框?

时间:2014-04-16 18:24:30

标签: wpf multithreading

我有一个带有进度条的“进度”对话框。该对话框作为Modal运行。但是有一个后台线程需要改变进度条的值。我正在使用Dispatcher.Invoke来确保我没有得到任何线程冲突。但这只有在对话框是非模态的情况下才有效。对于模态,我想它会阻止UI线程和Dispatcher.Invoke在UI线程中等待一些永远不会有的空闲时间。我该怎么做?

1 个答案:

答案 0 :(得分:1)

此代码将创建一个线程和一个窗口,其中进度条以模态显示。

System.Threading.ParameterizedThreadStart ts = new System.Threading.ParameterizedThreadStart((obj) => {
    System.Threading.Thread.Sleep(1000); // wait a second
    ProgressBar p = obj as ProgressBar;
    if (p != null)
    {
        double min = (double)p.Dispatcher.Invoke(new Func<double>(() => { return p.Minimum; }));
        double max = (double)p.Dispatcher.Invoke(new Func<double>(() => { return p.Maximum; }));
        for (var val = min; val <= max; val++)
        {
            System.Threading.Thread.Sleep(100);
            p.Dispatcher.Invoke(new Action(() => { p.Value = val; }));
        }
    }
});
System.Threading.Thread t = new System.Threading.Thread(ts);

Window w = new Window();
ProgressBar pb = new ProgressBar();
pb.Minimum = 0;
pb.Maximum = 100;
pb.Value = 0;
w.Content = pb;

MessageBox.Show("About to start thread and show dialog");
t.Start(pb);

w.ShowDialog();
MessageBox.Show("Dialog closed");