C#, WPF, Updating the gui without backgroundworkers

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

    If you don't want the background worker you need to adjust your code, to do the long task in the new thread.

    using System;
    using System.Threading;
    using System.Windows;
    
    namespace WpfApplication1
    {
      public partial class Window1 : Window
      {
          public Window1()
          {
              InitializeComponent();
    
              Thread t = new Thread(DoSomeLongTask);
              t.Start();
    
              // switch this with the DoSomeLongTask, so the long task is
              // on the new thread and the UI thread is free.
              ShowLoadingWindow();
        }
      }
    }
    

    If you want to then update a progress bar from your "DoSomeLongTask" method then you'll need to ensure that you call invoke. For example:

    delegate void ProgressDelegate(int Progress);  
    private void UpdateProgress( int  Progress)  
    {  
       if (!progressBar1.Dispatcher.CheckAccess())  
       {  
         progressBar1.Value = Progress;  
       }  
       else  
       {  
         ProgressDelegate progressD = new ProgressDelegate(UpdateProgress);  
         progressBar1.Dispatcher.Invoke(progressD, new object[] { Progress });  
       }  
    }  
    

提交回复
热议问题