在我的WPF C#项目中,我创建了一个内部有ProgressBar的Window。 当我需要进行长时间计算时,我会使用它,所以我会在计算结束前显示它。 从XAML可以看出这是一个无限制的进度条:
<ProgressBar x:Name="Solvers_ProgressBar" HorizontalAlignment="Left"
Height="30" Margin="36,53,0,0" VerticalAlignment="Top" Width="220"
Minimum="0" Maximum="100" IsIndeterminate="True"/>
它适用于所有情况但我在某个窗口中有问题。 我每次更改下拉列表时都会显示进度条,但有时候,进度条没有关闭并保持待定状态。
以下是具有进度条的窗口类的代码:
public class SolverProgressBarWindowHandler
{
private Thread StatusThread = null;
public SolversProgressBarWindow Popup = null;
public void Start()
{
//create the thread with its ThreadStart method
this.StatusThread = new Thread(() =>
{
try
{
this.Popup = new SolversProgressBarWindow();
this.Popup.Closed += (lsender, le) =>
{
//when the window closes, close the thread invoking the shutdown of the dispatcher
this.Popup.Dispatcher.InvokeShutdown();
this.Popup = null;
this.StatusThread = null;
};
this.Popup.ShowDialog();
//this call is needed so the thread remains open until the dispatcher is closed
System.Windows.Threading.Dispatcher.Run();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
}
});
//run the thread in STA mode to make it work correctly
this.StatusThread.SetApartmentState(ApartmentState.STA);
this.StatusThread.Priority = ThreadPriority.Normal;
this.StatusThread.Start();
}
public void Stop()
{
if (this.Popup != null)
{
//need to use the dispatcher to call the Close method, because the window is created in another thread, and this method is called by the main thread
this.Popup.Dispatcher.BeginInvoke(new Action(() =>
{
this.Popup.Close();
}));
}
}
}
调试代码,似乎有时候Popup
为空,所以Close方法不起作用。