2015.3.11 VS异步控件及进度条结合应用

1、在Form中添加 指针控件:BackgroundWorker-bgwork;进度条控件progressBar1 以及开始、取消按钮

2、开始按钮启动异步线程

private void button1_Click(object sender, EventArgs e)

{

   bgwork.WorkerReportsProgress = true; //允许异步控件报告状态

   bgwork.WorkerSupportsCancellation = true;//允许终止

   bgwork.RunWorkerAsync(new string[3] { "1", "2", "3" });//启动异步事件,其中可带任意参数e

}

3、执行异步函数

private void bgwork_DoWork(object sender, DoWorkEventArgs e)

{

    for (int i = 1; i < 101; i++)

    {

        Thread.Sleep(100);

        bgwork.ReportProgress(i); //触发bgwork_ProgressChanged事件,显示百分比i%

        if (bgwork.CancellationPending) //随时监测有无中止此后台进程

        {

            e.Cancel = true;//异步线程主动报告终止线程

            return;

        }

    }

}

private void bgwork_ProgressChanged(object sender, ProgressChangedEventArgs e)

{

    progressBar1.Value = e.ProgressPercentage; //主界面上显示进度条

}

中止后台进程

private void button2_Click(object sender, EventArgs e)

{

    bgwork.CancelAsync();  //主进程要求异步线程终止 此时bgwork.CancellationPending由false变为ture

}

异步进程中止和结构后触发事件

private void bgwork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

    if (e.Cancelled) MessageBox.Show("取消");//异步线程终止后,主进程判断退出原因,是主动取消还是出错退出。

    else MessageBox.Show(e.r);

}

posted on 2016-10-15 17:24  mol1995  阅读(329)  评论(0编辑  收藏  举报

导航