Winform c# 多线程处理实例
我们在用C# 开发程序时,经常会使用的多线程,实现多任务的处理。一般常用的方法是新建多个线程,进行处理。
今天我分享一个采用线程池的方式来实现的实例。对有需要的朋友做个借鉴。
实例: Winform
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; namespace MultiThreading { /// <summary> /// 此实例:为SDP软件快速开发平台中使用到的真实方法 /// </summary> public partial class Form1 : Form { /// <summary> /// 私有:线程同步信号 /// </summary> private ManualResetEvent cmdWaiter; /// <summary> /// 委托更新进度条 /// </summary> private delegate void updateBar(); /// <summary> /// 结束提示委托 /// </summary> private delegate void showEnd(); /// <summary> /// 任务队列 /// 注意:此任务队列 需要用户自动来定义 /// 实例中采用 string 来处理 /// </summary> private List<string> taskList = new List<string>(); /// <summary> /// 构造函数 /// </summary> public Form1() { InitializeComponent(); } /// <summary> /// 页面初始化加载 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load(object sender, EventArgs e) { // 阻塞当前线程 cmdWaiter = new ManualResetEvent(false); // 启动线程池 ThreadPool.QueueUserWorkItem(new WaitCallback(this.On_ThreadEvent)); } /// <summary> /// 线程处理事务 /// </summary> /// <param name="obj"></param> private void On_ThreadEvent(object obj) { while (true) { try { // 阻塞当前线程,等待解除指令 this.cmdWaiter.WaitOne(); // 执行我们需要处理的事务 for (int k = 0; k < taskList.Count; k++) { Run_MyBusiness(taskList[k]); // 休息指定的毫秒 Thread.Sleep(50); } // 清除队列数据 this.taskList.Clear(); this.On_EndLog(); this.cmdWaiter.Reset(); } catch (Exception e) { string strError = e.Message.ToString(); this.taskList.Clear(); this.cmdWaiter.Reset(); } } } /// <summary> /// 执行我们自己的业务 /// </summary> /// <param name="str"></param> private void Run_MyBusiness(string str) { // 委托更新 updateBar updateDelegate = new updateBar(On_Update); this.Invoke(updateDelegate); } /// <summary> /// 开始按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Start_Click(object sender, EventArgs e) { this.taskList = new List<string>(); for (int i = 1; i < 1001; i++) { this.taskList.Add(i.ToString()); } this.txt_log.Text = "开始:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine; this.pg_Bar.Value = 0; this.pg_Bar.Maximum = this.taskList.Count; // 解除阻塞 this.cmdWaiter.Set(); } /// <summary> /// 更新进度条 /// </summary> private void On_Update() { this.pg_Bar.Value = this.pg_Bar.Value + 1; } private void On_EndLog() { showEnd endDeg = new showEnd(On_UpdateTextBox); this.Invoke(endDeg); } private void On_UpdateTextBox() { string runStr = "结束:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); this.txt_log.Text = this.txt_log.Text + runStr; } } }
运行效果:
下载地址:多线程实例 DEMO