• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

ces

开发技术 开发技术 3天前 8次浏览

`
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BackgroundWorkTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

    /// <summary>
    /// 开始运行按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnStart_Click(object sender, EventArgs e)
    {
        if (backgroundWorker1.IsBusy)
        {
            MessageBox.Show("正在运行线程");
            return;
        }

        backgroundWorker1.RunWorkerAsync(1000);
    }

    /// <summary>
    /// 后台组件工作中运行的代码
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e">e.Argument传递的数值</param>
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int n = 0;
        int sum = 0;
        //获取异步操作的数值
        if (e.Argument != null)
        {
            n = (int)e.Argument;
        }

        for (int i = 0; i < n; i++)
        {
            //是否取消后台操作
            if (backgroundWorker1.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
            sum += i;
            Thread.Sleep(10);
            //通过计算,传递值为100.比如i=1000,i / 10 = 100;
            backgroundWorker1.ReportProgress(i / 10, "当前i的值为" + Convert.ToString(i));
        }
        //异步操作结果的值
        e.Result = sum;
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        //注意value数值不能大于100
        progressBar1.Value = e.ProgressPercentage;
        label1.Text = e.UserState.ToString();
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //异步操作期间是否出错
        if (!(e.Error == null))
        {
            MessageBox.Show(e.Error.Message);
            return;
        }

        //异步操作期间是否取消
        if (e.Cancelled)
        {
            progressBar1.Value = 0;
            label1.Text = "";
            MessageBox.Show("取消线程的执行");
            return;
        }

        label1.Text = "计算结果:" + e.Result.ToString();
     //   this.progressBar1.Value = 100;
    }

    /// <summary>
    /// 取消按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnCancel_Click(object sender, EventArgs e)
    {
        if (!backgroundWorker1.IsBusy) return;

        //取消后台操作
        backgroundWorker1.CancelAsync();

    }
}

}
`


程序员灯塔
转载请注明原文链接:ces
喜欢 (0)