C#多线程BackgroundWorker使用示例

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

namespace BackgroundWorkerSample
{
    public partial class CalculateAddForm : Form
    {
        protected BackgroundWorker backgroundWorker1 = new BackgroundWorker();
        //private int numberToCompute = 0;
        //private int highestPercentageReached = 0;

        public CalculateAddForm()
        {
            InitializeComponent();

            InitializeBackgoundWorker();
           
        }

        // Set up the BackgroundWorker object by
        // attaching event handlers.
        private void InitializeBackgoundWorker()
        {
            this.backgroundWorker1.WorkerReportsProgress = true;
            this.backgroundWorker1.WorkerSupportsCancellation = true;
           
            this.backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
        }

        private long ComputeAdd(int n, BackgroundWorker worker, DoWorkEventArgs e)
        {
            long result = 0;

            // Abort the operation if the user has canceled.
            // Note that a call to CancelAsync may have set
            // CancellationPending to true just after the
            // last invocation of this method exits, so this
            // code will not have the opportunity to set the
            // DoWorkEventArgs.Cancel flag to true. This means
            // that RunWorkerCompletedEventArgs.Cancelled will
            // not be set to true in your RunWorkerCompleted
            // event handler. This is a race condition.

            for (int i = 1; i <= n; i++)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    result += i;
                    Thread.Sleep(100);
                    // Report progress as a percentage of the total task.
                    int percentComplete = (int)((float)i / (float)n * 100);
                    worker.ReportProgress(percentComplete);
                }
            }
            return result;
        }
       
        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // Get the BackgroundWorker that raised this event.
            BackgroundWorker worker = sender as BackgroundWorker;

            // Assign the result of the computation
            // to the Result property of the DoWorkEventArgs
            // object. This is will be available to the
            // RunWorkerCompleted eventhandler.
            e.Result = ComputeAdd((int)e.Argument, worker, e);
           
            // If the operation was canceled by the user,
            // set the DoWorkEventArgs.Cancel property to true.
            if (worker.CancellationPending)
            {
                e.Cancel = true;
            }
        }

        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }

        void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // First, handle the case where an exception was thrown.
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                // Next, handle the case where the user canceled
                // the operation.
                // Note that due to a race condition in
                // the DoWork event handler, the Cancelled
                // flag may not have been set, even though
                // CancelAsync was called.
                resultLabel.Text = "Canceled";
            }
            else
            {
                // Finally, handle the case where the operation
                // succeeded.
                resultLabel.Text = e.Result.ToString();
            }

            // Enable the UpDown control.
            this.numericUpDown1.Enabled = true;

            // Enable the Start button.
            startAsyncButton.Enabled = true;

            // Disable the Cancel button.
            cancelAsyncButton.Enabled = false;

        }

       
        private void startAsyncButton_Click(object sender, EventArgs e)
        {
            // Reset the text in the result label.
            resultLabel.Text = String.Empty;

            // Disable the UpDown control until
            // the asynchronous operation is done.
            this.numericUpDown1.Enabled = false;

            // Disable the Start button until
            // the asynchronous operation is done.
            this.startAsyncButton.Enabled = false;

            // Enable the Cancel button while
            // the asynchronous operation runs.
            this.cancelAsyncButton.Enabled = true;

            // Get the value from the UpDown control.
            int numberToCompute = (int)numericUpDown1.Value;

            // Reset the variable for percentage tracking.
            //highestPercentageReached = 0;

            // Start the asynchronous operation.
            backgroundWorker1.RunWorkerAsync(numberToCompute);

        }

        private void cancelAsyncButton_Click(object sender, EventArgs e)
        {
            // Cancel the asynchronous operation.
            this.backgroundWorker1.CancelAsync();

            // Disable the Cancel button.
            cancelAsyncButton.Enabled = false;

        }       
    }
}
 

时间: 2024-10-30 11:02:06

C#多线程BackgroundWorker使用示例的相关文章

多线程BackgroundWorker

链接:http://www.cnblogs.com/yiyisawa/archive/2008/11/24/1339826.html 周六闲来无事,学习了多线程BackgroundWorker,以此记录.  此案例功能:      实现用BackgroundWorker处理进度条,可以开始,暂停,继续,清空.  BackgroundWorker说明:   摘抄自---http://msdn.microsoft.com       BackgroundWorker 类允许您在单独的专用线程上运行操

php与python实现的线程池多线程爬虫功能示例_php技巧

本文实例讲述了php与python实现的线程池多线程爬虫功能.分享给大家供大家参考,具体如下: 多线程爬虫可以用于抓取内容了这个可以提升性能了,这里我们来看php与python 线程池多线程爬虫的例子,代码如下: php例子 <?php class Connect extends Worker //worker模式 { public function __construct() { } public function getConnection() { if (!self::$ch) { sel

C语言编程中借助pthreads库进行多线程编程的示例_C 语言

运行之前需要做一些配置: 1.下载PTHREAD的WINDOWS开发包 pthreads-w32-2-4-0-release.exe(任何一个版本均可)    http://sourceware.org/pthreads-win32/ ,解压到一个目录. 2.找到include和lib文件夹,下面分别把它们添加到VC++6.0的头文件路径和静态链接库路径下面:    a).Tools->Options,选择Directory页面,然后在Show directories for:中选择Includ

Android多线程断点续传下载示例详解

一.概述 在上一篇博文<Android多线程下载示例>中,我们讲解了如何实现Android的多线程下载功能,通过将整个文件分成多个数据块,开启多个线程,让每个线程分别下载一个相应的数据块来实现多线程下载的功能.多线程下载中,可以将下载这个耗时的操作放在子线程中执行,即不阻塞主线程,又符合Android开发的设计规范. 但是当下载的过程当中突然出现手机卡死,或者网络中断,手机电量不足关机的现象,这时,当手机可以正常使用后,如果重新下载文件,似乎不太符合大多数用户的心理期望,那如何实现当手机可以正

Java多线程的同步示例及对象锁机制

java多线程的同步依靠的是对象锁机制,synchronized关键字的背后就是利用了封锁来实现对共享资源的互斥访问. 下面以一个简单的实例来进行对比分析.实例要完成的工作非常简单,就是创建10个线程,每个线程都打印从0到99这100个数字,我们希望线程之间不会出现交叉乱序打印,而是顺序地打印. 先来看第一段代码,这里我们在run()方法中加入了synchronized关键字,希望能对run方法进行互斥访问,但结果并不如我们希望那样,这 是因为这里synchronized锁住的是this对象,即

android使用多线程更新ui示例分享_Android

Android线程涉及的技术有:Handler;Message;MessageQueue;Looper;HandlerThread. 下面看一段在线程中更新UI的代码: 复制代码 代码如下: public class MainActivity extends Activity {private TextView timeLable;private Button stopBtn;private Thread mThread;private boolean isRunning = true;priv

c语言实现多线程动画程序示例_C 语言

该程序是利用opengl图形库与fmod音频库写的一个简单3d动画程序.该程序在vs下运行良好,若缺少相关dll文件请确认已配制fmod与opengl库. mixmodel.cpp 复制代码 代码如下: // mixmodel.cpp : 定义控制台应用程序的入口点.// #include "stdafx.h" //定义一个线程DWORD WINAPI SoundProc( LPVOID LPVIDEOPARAMETERS);//光照变量GLfloat  whiteLight[] =

python多线程扫描端口示例_python

复制代码 代码如下: # -*- coding: cp936 -*-import socketfrom threading import Thread,activeCount,Lockfrom time import ctimemutex = Lock() class Loop(Thread):    def __init__(self,ip,port,que):        Thread.__init__(self)        self.ip     = ip        self.p

java多线程读写文件示例_java

复制代码 代码如下: package com.ysh.file; import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock; import c