如何使用WPF后台工作 [英] How to use WPF Background Worker

查看:119
本文介绍了如何使用WPF后台工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个初学者的 WPF 后,在我的应用程序需要执行一系列的初始化步骤,这些都需要7-8秒钟即可完成在这期间我的UI变得反应迟钝。要解决这一点,我在一个单独的线程执行初始化:

I am a beginner with WPF, in my application I need to perform a series of initialisation steps, these take 7-8 seconds to complete during which my UI becomes unresponsive. To resolve this I perform the initialisation in a separate thread:

    public void Initialization()
    {
        Thread initThread = new Thread(new ThreadStart(InitializationThread));
        initThread.Start();
    }

    public void InitializationThread()
    {
        outputMessage("Initializing...");
        //DO INITIALIZATION
        outputMessage("Initialization Complete");
    }

我已阅读有关的BackgroundWorker 几篇文章以及应该如何让我保持我的应用程序响应而不必写一个线程来执行长时间的任务,但我避风港'T有任何成功的努力来实现它,任何人都可以告诉我怎么会用这样做的的BackgroundWorker

I have read a few articles about the BackgroundWorker and how it should allow me to keep my application responsive without ever having to write a thread to perform lengthy tasks but I haven't had any success trying to implement it, could anyone tell how I would do this using the BackgroundWorker?

谢谢,
埃蒙·

Thanks, Eamonn

推荐答案

1.新增如下使用:使用System.ComponentModel;

1.Add following using: using System.ComponentModel;

2.Declare <一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\">background工人:

2.Declare background worker:

private readonly BackgroundWorker worker = new BackgroundWorker();

3.Subscribe事件:

3.Subscribe to events:

worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;

4.Implement两种方法:

4.Implement two methods:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
   // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender, 
                                       RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete his work
}

5.Run工人异步每当您的需要。

5.Run worker async whenever your need.

worker.RunWorkerAsync();

此外,如果你要举报你应该订阅 ProgressChanged 事件和使用过程中的进展 ReportProgress(Int32)已的DoWork 方法引发事件。还设置如下: worker.WorkerReportsProgress = TRUE; (感谢@zagy)

Also if you want to report process progress you should subscribe to ProgressChanged event and use ReportProgress(Int32) in DoWork method to raise an event. Also set following: worker.WorkerReportsProgress = true; (thanks to @zagy)

希望这有助于。

这篇关于如何使用WPF后台工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆