创建线程的几种方式(代码示例)
2014-03-05 23:34
465 查看
[code] #region 方式2-1 启动线程(带输入参数的) private void btn1_Click(object sender, EventArgs e) { MyObject obj = new MyObject(1, 2);//或者使用全局变量代替obj Thread thread = new Thread(obj.FunctionName); thread.Start(); } public class MyObject { public int a1, b1; public MyObject(int a, int b) { a1 = a; b1 = b; } public void FunctionName() { MessageBox.Show("a:" + a1 + ",b:" + b1); } } #endregion #region 方式2-2 启动线程(带输入参数的) private void btn2_Click(object sender, EventArgs e) { //这个Thread类的构造方法的定义如下: Thread thread = new Thread(myStaticParamThreadMethod); thread.Start("通过委托的参数传值"); } public static void myStaticParamThreadMethod(Object obj) { MessageBox.Show(obj.ToString()); } //[ComVisibleAttribute(false)] //public delegate void ParameterizedThreadStart(Object obj); //public Thread(ParameterizedThreadStart start); #endregion #region 方式3 线程池技术 RegisteredWaitHandle RW; private void btn3_Click(object sender, EventArgs e) { //ThreadPool.QueueUserWorkItem((objState) => //{ // //do something.. //from the thread pool. //}, null); RW = ThreadPool.RegisterWaitForSingleObject(wait, new WaitOrTimerCallback(test), state, 1000, false); wait.Set(); } AutoResetEvent wait = new AutoResetEvent(false); object state = new object(); int count = 0; /// <summary> /// 会定时反复调用 /// </summary> private void test(object state, bool timedOut) { SetText(DateTime.Now.ToString()); count++; if (count > 5) RW.Unregister(wait);//执行5次后,退出 } /// <summary> /// 调用UI线程,修改界面数据 /// </summary> public void SetText(string argText) { if (lblResult.InvokeRequired) { lblResult.Invoke(new SetTextDelegateMethod(SetText), new[] { argText }); } else lblResult.Text = argText; } public delegate void SetTextDelegateMethod(string argText); #endregion #region 方式4 使用BackgroundWorker //支持:报告进度、支持完成回调、取消任务、暂停任务等 private BackgroundWorker Worker; private void btn4_Click(object sender, EventArgs e) { Worker = new BackgroundWorker(); Worker.WorkerReportsProgress = true; Worker.WorkerSupportsCancellation = true; Worker.DoWork += worker_DoWork; Worker.ProgressChanged += worker_ProgressChanged; Worker.RunWorkerCompleted += worker_RunWorkerCompleted; Worker.RunWorkerAsync(); } /// <summary> /// 异步执行完毕,回到UI线程 /// </summary> void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled) lblResult.Text = "取消成功!"; else lblResult.Text = "执行完成!"; ////测试捕获异常 //if (e.Error != null && !string.IsNullOrEmpty(e.Error.Message)) lblResult.Text = e.Error.Message; //借助AsyncOperation.Post(SendOrPostCallback d, object arg), //在winform下使用这个函数,使得由SendOrPostCallback定义被封送回UI线程 } private void btn4Abort_Click(object sender, EventArgs e) { Worker.CancelAsync(); } void worker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker _worker = sender as BackgroundWorker; for (int i = 1; i < 101; i++) { _worker.ReportProgress(i, "执行到第" + i + "个"); Thread.Sleep(100); //此时在非UI线程中执行代码,执行下行代码会出错 //lblResult.Text = "aaa"; //线程间操作无效: 从不是创建控件“lblResult”的线程访问它。 //这里判断一下是否用户要求取消后台进行,并可以尽早退出 if (_worker.CancellationPending) { e.Cancel = true; return; } ////测试捕获异常 //if (i == 35) throw new Exception("在执行到i=" + i + "时候出错!"); } } void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { this.lblResult.Text = e.ProgressPercentage.ToString() + " " + e.UserState; } #endregion
[/code]
namespace WinFormsApp_CreateAThread { partial class Form1 { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.btn1 = new System.Windows.Forms.Button(); this.btn2 = new System.Windows.Forms.Button(); this.btn3 = new System.Windows.Forms.Button(); this.lblResult = new System.Windows.Forms.Label(); this.btn4 = new System.Windows.Forms.Button(); this.btn4Abort = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btn1 // this.btn1.Location = new System.Drawing.Point(24, 99); this.btn1.Name = "btn1"; this.btn1.Size = new System.Drawing.Size(141, 44); this.btn1.TabIndex = 0; this.btn1.Text = "创建线程并带参数传值1"; this.btn1.UseVisualStyleBackColor = true; this.btn1.Click += new System.EventHandler(this.btn1_Click); // // btn2 // this.btn2.Location = new System.Drawing.Point(24, 174); this.btn2.Name = "btn2"; this.btn2.Size = new System.Drawing.Size(141, 39); this.btn2.TabIndex = 1; this.btn2.Text = "创建线程并带参数传值2"; this.btn2.UseVisualStyleBackColor = true; this.btn2.Click += new System.EventHandler(this.btn2_Click); // // btn3 // this.btn3.Location = new System.Drawing.Point(211, 174); this.btn3.Name = "btn3"; this.btn3.Size = new System.Drawing.Size(131, 39); this.btn3.TabIndex = 2; this.btn3.Text = "通过线程池创建线程3"; this.btn3.UseVisualStyleBackColor = true; this.btn3.Click += new System.EventHandler(this.btn3_Click); // // lblResult // this.lblResult.AutoSize = true; this.lblResult.Location = new System.Drawing.Point(236, 115); this.lblResult.Name = "lblResult"; this.lblResult.Size = new System.Drawing.Size(41, 12); this.lblResult.TabIndex = 3; this.lblResult.Text = "label1"; // // btn4 // this.btn4.Location = new System.Drawing.Point(211, 236); this.btn4.Name = "btn4"; this.btn4.Size = new System.Drawing.Size(150, 44); this.btn4.TabIndex = 4; this.btn4.Text = "使用BackgroundWorker 4"; this.btn4.UseVisualStyleBackColor = true; this.btn4.Click += new System.EventHandler(this.btn4_Click); // // btn4Abort // this.btn4Abort.Location = new System.Drawing.Point(211, 286); this.btn4Abort.Name = "btn4Abort"; this.btn4Abort.Size = new System.Drawing.Size(150, 44); this.btn4Abort.TabIndex = 5; this.btn4Abort.Text = "4 取消当前操作"; this.btn4Abort.UseVisualStyleBackColor = true; this.btn4Abort.Click += new System.EventHandler(this.btn4Abort_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(399, 339); this.Controls.Add(this.btn4Abort); this.Controls.Add(this.btn4); this.Controls.Add(this.lblResult); this.Controls.Add(this.btn3); this.Controls.Add(this.btn2); this.Controls.Add(this.btn1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btn1; private System.Windows.Forms.Button btn2; private System.Windows.Forms.Button btn3; private System.Windows.Forms.Label lblResult; private System.Windows.Forms.Button btn4; private System.Windows.Forms.Button btn4Abort; } }
[/code]
相关文章推荐
- C++中引用与指针的区别
- Struts文件上传allowedTypes/allowedExtensions问题
- C语言中字符串结束符探究
- C/C++产生随机数【作者:江南烟雨梦】
- 【JAVA】设计模式之命令模式(Command模式)的使用分析
- LeetCode | Gray Code
- MyEclipse开发WebService教程
- C语言链表实现冒泡法排序
- JavaSE 8 :Lambda 快速学习(三)
- java第一天
- java逻辑运算符位运算符总结
- jpush使用的一系列问题
- PHP学习之九:扩展函数库之字符串与数据库访问等
- C++ 标准库的 locale 类用法 .
- php数组工具类 php数组与对象、字符串的转换实例
- Java 排序
- Struts2框架中 怎么把从数据库中读取的数据生成文件,并在客户端保存
- JDK安装并配置环境变量以及tomact解压版加载到MYeclipse
- wpf后台代码数据绑定
- Twitter Storm源代码分析之TimeCacheMap-过期清除