主窗口加载时WPF BackgroundWorker

时间:2015-01-04 08:19:04

标签: c# wpf backgroundworker

我有主窗口的WPF应用程序。我希望BackgroundWorker在主窗口加载时打开一个加载窗口(WinLoading),并在加载完成时关闭它。我在主窗口中有这个代码。当我运行它时,我会在主窗口打开之前(10秒后)完成操作后打开WinLoading窗口。

public MainWindow()
    {
        InitializeComponent();

        wLoadingService = new BackgroundWorker();
        wLoadingService.DoWork += wLoadingService_DoWork;
        wLoadingService.RunWorkerCompleted += wLoadingService_RunWorkerCompleted;
        wLoadingService.WorkerReportsProgress = true;
        wLoadingService.WorkerSupportsCancellation = true;
        wLoadingService.RunWorkerAsync();

        //some action (takes 10 seconds).....
    }

    void wLoadingService_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        this.Dispatcher.Invoke((Action)(() =>
        {
            WinLoading.EndDisplay();
        }));
    }

    void wLoadingService_DoWork(object sender, DoWorkEventArgs e)
    {
        this.Dispatcher.Invoke((Action)(() =>
        {
            WinLoading.Loading("Connecting...");
            WinLoading.BeginDisplay();
        }));
    }

1 个答案:

答案 0 :(得分:1)

使用this.Dispatcher.Invoke显式在主UI线程上运行工作。这有效地使你的后台工作者无用,迫使它等到主线程完成“某个动作”。

“某些行动”是这里长期运作的任务。 那个是你想要从后台工作者执行的代码,而你的主线程处理WinLoading对话框。

相关问题