C#, WPF, Updating the gui without backgroundworkers

后端 未结 3 1520
有刺的猬
有刺的猬 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:14

    You're still doing the long task in the main thread. You need to show the loading window in the main thread and do the long task in the background.

    Using a BackgroundWorker is really the simplest solution for this:

    BackgroundWorker bw;
    LoadingWindow lw;
    
    public Window1() {
        bw = new BackgroundWorker();
        lw = new LoadingWindow();
    
        bw.DoWork += (sender, args) => {
            // do your lengthy stuff here -- this will happen in a separate thread
            ...
        }
    
        bw.RunWorkerCompleted += (sender, args) => {
            if (args.Error != null)  // if an exception occurred during DoWork,
                MessageBox.Show(args.Error.ToString());  // do your error handling here
    
            // close your loading window here
            ...
        }
    
        // open and show your loading window here
        ...
    
        bw.RunWorkerAsync(); // starts the background worker
    }
    

提交回复
热议问题