在SeperateThread

时间:2016-06-27 12:37:24

标签: c# wpf multithreading

我有一种方法可以将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方法导出时动画不会冻结?

1 个答案:

答案 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();
}));