我这样做是为了解决问题。不过,我也有同样的问题。如何修改下面的代码来解决此问题?

            TimeWindow aTimeWindow = new TimeWindow();
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += ((o, ea) => {
                // Highly time consumable task
                _resetEvent.Set();
            });
            aTimeWindow.Show();
            bw.RunWorkerAsync();
            _resetEvent.WaitOne();
            aTimeWindow.Close();

_resetEvent是一个类字段。TimeWindow只是一个带有wpf控件的图像。

最佳答案

您可以异步/等待,以便在工作完成时显示并关闭窗口。类似于:

private async void ShowWindow()
{
    var aTimeWindow = new TimeWindow();
    aTimeWindow.Show();
    await Task.Run((Action)DoWork);
    aTimeWindow.Close();
}

private void DoWork()
{
    // perform long running work here
}

编辑:
不使用async/await
private void ShowWindow()
{
    var aTimeWindow = new TimeWindow();
    aTimeWindow.Show();

    Task.Run(()=>
    {
        DoWork();
    })
    .ContinueWith((t) =>
    {
        Application.Current.Dispatcher.BeginInvoke((Action)(() =>
        {
            aTimeWindow.Close();
        }));
    });
}

private void DoWork()
{
    // perform long running work here
}

10-08 04:57