zoukankan      html  css  js  c++  java
  • BackgroundWroker使用方法备忘

    using System;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Threading;

    namespace WindowsFormsApplication1
    {
    publicpartialclass Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    worker
    =new BackgroundWorker();
    worker.DoWork
    +=new DoWorkEventHandler(worker_DoWork);
    worker.ProgressChanged
    +=new ProgressChangedEventHandler(worker_ProgressChanged);
    worker.RunWorkerCompleted
    +=new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
    worker.WorkerReportsProgress
    =true; //允许进度显示
    worker.WorkerSupportsCancellation =true; //允许运行中取消
    }

    BackgroundWorker worker;

    privatevoid Form1_Load(object sender, EventArgs e)
    {

    }

    privatevoid worker_DoWork(object sender, DoWorkEventArgs e)
    {
    for (int i =0; i <300; i++)
    {
    Thread.Sleep(
    100);
    //每隔一段时间就向主线程报告进度,以便更新进度条。
    //多数情况下,你只需要发送一个整数去更新即可
    worker.ReportProgress(i/3);
    if (worker.CancellationPending)
    {
    //如果任务被取消
    e.Cancel =true;
    worker.ReportProgress(
    0);
    return;
    }
    }
    }

    privatevoid worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    pbarThis.Value
    = e.ProgressPercentage;
    lblText.Text
    ="已经处理了 "+ pbarThis.Value.ToString() +"%";
    }

    privatevoid worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    if (e.Cancelled)
    {
    lblText.Text
    ="任务取消";
    }
    elseif (e.Error !=null)
    {
    lblText.Text
    ="发生错误";
    }
    else
    {
    lblText.Text
    ="任务完成";
    }
    btnStart.Enabled
    =true;
    btnCancel.Enabled
    =false;
    }

    privatevoid btnStart_Click(object sender, EventArgs e)
    {
    btnStart.Enabled
    =false;
    btnCancel.Enabled
    =true;

    //通知主线程开始进行数据处理
    worker.RunWorkerAsync();
    }

    privatevoid btnCancel_Click(object sender, EventArgs e)
    {
    if (worker.IsBusy)
    {

    worker.CancelAsync();
    }
    }
    }
    }
  • 相关阅读:
    wap2app(五)-- 微信授权登录以及踩过的坑
    wap2app(六)-- wap2app的原生标题头无法隐藏
    创建对象的几种模式
    通过url动态获取图片大小方法总结
    wap2app(三)-- 添加引导页
    wap2app(二)-- 设置APP系统状态栏
    wap2app(一)-- 网站快速打包成app
    树叶飘落、雪花飘落等同时多个图片飘落
    基于bootstrap的双日历插件 daterangepicker
    FileProvider解决FileUriExposedException
  • 原文地址:https://www.cnblogs.com/scy251147/p/2145197.html
Copyright © 2011-2022 走看看