我有一个应用程序可能需要很长时间才能执行一些 GUI 更新。我不能在后台线程中运行它,因为长时间处理与更新只能在主线程中完成的 GUI 组件相关联。
因此,我创建了一个辅助类,它将在后台线程中创建并显示一个 WaitDialog 表单,直到 GUI 完成更新。
我的助手类如下所示:
public class ProgressWaitDialogHelper : IDisposable
{
private Thread _thread = null;
public void ShowDialog()
{
ThreadStart threadStart = new ThreadStart(ShowDialogAsync);
_thread = new Thread(threadStart);
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();
}
public void Dispose()
{
if ((_thread != null) &&
(_thread.IsAlive))
{
_thread.Abort();
}
}
private void ShowDialogAsync()
{
ProgressWaitDialog waitDialog = new ProgressWaitDialog();
waitDialog.ShowDialog();
}
}
在我的主 GUI 窗口中调用帮助程序类的代码如下所示:
using (ProgressWaitDialogHelper waitDialog = new ProgressWaitDialogHelper())
{
waitDialog.ShowDialog();
// Do long running GUI task on main thread here.
}
这似乎工作正常,看起来就像我在 GUI 上想要的一样。WaitDialog 表单是模态的,在完成更新之前会阻止对主 GUI 表单的访问。一旦长时间运行的 GUI 任务完成,它将退出 Using 块,从而调用助手类的 Dispose 方法,该方法又将调用线程上的 Abort。
我的问题是,是否有更优雅的方式来终止线程或实现相同行为的更好方式?