我有一种方法可以将DataGrid
的内容导出到CSV
文件。我试图显示一个有动画的Window
,要求用户等待。
但是,当我显示Window
动画冻结时,我认为这是因为excel方法在同一个线程上运行时会冻结。
到目前为止我所尝试的是这个;
var waitWindow = new PleaseWaitWindow();
var newWindowThread = new Thread(() =>
{
waitWindow.Show();
System.Windows.Threading.Dispatcher.Run();
});
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();
ExcelExport();
waitWindow.Close();
但这会导致错误;
The calling thread cannot access this object because a different thread owns it.
如何启动新线程,以便在excel方法导出时动画不会冻结?
答案 0 :(得分:1)
您需要将窗口的创建移动到新的线程中,使用ShowDialog
确保它通过自己的Dispatcher
阻止并关闭它。
PleaseWaitWindow waitWindow = null;
var newWindowThread = new Thread(() =>
{
waitWindow = new PleaseWaitWindow();
waitWindow.ShowDialog();
}
);
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.Start();
ExcelExport();
waitWindow.Dispatcher.BeginInvoke(new Action(() =>
{
waitWindow.Close();
}));
在尝试关闭它之前确保waitWindow
已创建,某种IPC屏障在这里会很好。例如(快速和脏):
PleaseWaitWindow waitWindow = null;
AutoResetEvent loaded = new AutoResetEvent(false);
var newWindowThread = new Thread(() =>
{
waitWindow = new PleaseWaitWindow();
loaded.Set();
waitWindow.ShowDialog();
});
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.Start();
ExcelExport();
loaded.WaitOne();
waitWindow.Dispatcher.BeginInvoke(new Action(() =>
{
waitWindow.Close();
}));