C#, WPF, Updating the gui without backgroundworkers

后端 未结 3 1525
有刺的猬
有刺的猬 2021-02-11 06:27

I have a program that takes 10-20 seconds to start. I need to show a window with a progress bar when the program starts up. I know BackgroundWorker\'s are the correct way to do

3条回答
  •  抹茶落季
    2021-02-11 07:07

    It really is very easy to use backgroundworker.

    public partial class Window1 : Window
    {
        BackgroundWorker worker = new BackgroundWorker();
    
        public Window1()
        {
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.ReportsProgress = true;
            worker.ProgressChanged += new ProgressChangedEventHandler(update_progress);
        }
    
    
        void worker_DoWork(object sender, DoWorkEventArgs e){
            DoSomeLongTask();
            //call worker.ReportProgress to update bar
        }
    
        void update_progress(object sender, ProgressChangedEventArgs e)
        {
            myscrollbar.Value = e.Value;
        }
    }
    

    The keything to keep in mind is to never touch gui stuff from DoWork method. That has to through ProgressChanged/ReportProgress

提交回复
热议问题