How to use WPF Background Worker

Total Post:89


 1726  View(s)
Rate this:

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

    public void Initialization()


        Thread initThread = new Thread(new ThreadStart(InitializationThread));



    public void InitializationThread()




        outputMessage("Initialization Complete");


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 preform lengthy tasks but I haven't had any success trying to implement it, could anyone tell how I would do this using the BackgroundWorker?

  1. Re: How to use WPF Background Worker

    Hi Takeshi,

    Add following using: using System.ComponentModel;

    1.Declare backgrownd worker:

    private readonly BackgroundWorker worker = new BackgroundWorker();

    2.Subscribe to events:

    worker.DoWork += worker_DoWork;

    worker.RunWorkerCompleted += worker_RunWorkerCompleted;

    3.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

    4.Run worker async whenever your need.


    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)

    Hope this help.

      Modified On Mar-31-2018 01:54:36 AM


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.