How to use WPF Background Worker

前端 未结 4 1218
孤独总比滥情好
孤独总比滥情好 2020-11-22 05:53

In my application I need to perform a series of initialization steps, these take 7-8 seconds to complete during which my UI becomes unresponsive. To resolve this I perform t

4条回答
  •  春和景丽
    2020-11-22 06:38

    1. Add using
    using System.ComponentModel;
    
    1. Declare Background Worker:
    private readonly BackgroundWorker worker = new BackgroundWorker();
    
    1. Subscribe to events:
    worker.DoWork += worker_DoWork;
    worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    
    1. 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
    }
    
    1. Run worker async whenever your need.
    worker.RunWorkerAsync();
    
    1. Track progress (optional, but often useful)

      a) subscribe to ProgressChanged event and use ReportProgress(Int32) in DoWork

      b) set worker.WorkerReportsProgress = true; (credits to @zagy)

提交回复
热议问题