其他分享
首页 > 其他分享> > BackgroundWorker类的案例

BackgroundWorker类的案例

作者:互联网

  
public partial class MainWindow : Window
    {
        BackgroundWorker bgWorker = new BackgroundWorker();
        public MainWindow()
        {
            InitializeComponent();
            //设置属性
            bgWorker.WorkerReportsProgress = true;
            bgWorker.WorkerSupportsCancellation = true;
        //链接BackgroundWorker的事件处理程序。
        bgWorker.DoWork += DoWork_Handle;
        bgWorker.ProgressChanged += ProgressChanged_Handle;
        bgWorker.RunWorkerCompleted += RunWorkerCompleted_Handle;
    }
    
    private void btnProcess_Click(object sender, RoutedEventArgs e)
    {
        if (!bgWorker.IsBusy)
        {
            bgWorker.RunWorkerAsync();
        }
        
    }

    private void btnCancel_Click(object sender, RoutedEventArgs e)
    {
        bgWorker.CancelAsync();
    }
    private void DoWork_Handle(object sender,DoWorkEventArgs args)
    {
        BackgroundWorker worker = sender as BackgroundWorker;//显示的转换给定类型。
        for (int i = 0; i <=10; i++)
        {
            if (worker.CancellationPending)
            {
                args.Cancel = true;
                break;
            }
            else
            {
                worker.ReportProgress(i * 10);
                Thread.Sleep(500);
            }
        }
    }
    private  void ProgressChanged_Handle(object sender, ProgressChangedEventArgs args)
    {

        progressBar.Value = args.ProgressPercentage;
    }
    private void RunWorkerCompleted_Handle(object sender,RunWorkerCompletedEventArgs args)
    {
        progressBar.Value = 0;
        if (args.Cancelled)
        {
            MessageBox.Show("Process was Canceled", "Process Cancelled");
        }
        else
        {

            MessageBox.Show("Process was Completed", "Process Completed");
        }


    }
}

标签:Handle,sender,DoWork,bgWorker,BackgroundWorker,案例,private
来源: https://www.cnblogs.com/caiwenwen/p/15893527.html