线程 和异步委托

本文通过一个具体的Windows Forms应用示例介绍了如何使用异步委托和线程来更新UI进度条,展示了两种不同并发任务执行的方式及其对UI线程的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace 异步委托和线程调用
{
 
/// <summary>
 
/// Form1 的摘要说明。
 
/// </summary>

 public class Form1 : System.Windows.Forms.Form
 
{
默认代码
  
  
//线程
  private void button1_Click(object sender, System.EventArgs e)
  
{
   System.Threading.Thread th 
= new System.Threading.Thread(
    
new System.Threading.ThreadStart(Fun2));   
   
this.processEvent += new myProcessEventHandle(Form1_processEvent);
   th.Start();
   button2.Enabled 
= false;
  }


  
//异步委托
  private void button2_Click(object sender, System.EventArgs e)
  
{
   System.Threading.WaitCallback wc 
= new System.Threading.WaitCallback(Fun);
   
object obj = this.button1;//这里没用。到时候你可以用来传递参数
   this.processEvent += new myProcessEventHandle(Form1_processEvent);
   System.Threading.ThreadPool.QueueUserWorkItem(wc,obj);   
   button1.Enabled 
= false;
  }


  
public delegate void myProcessEventHandle(int percent);//定义事件
  public event myProcessEventHandle processEvent = null;//事件声明

  

  
//线程无法带参数启动,和这个函数通讯直接用成员变量就可以了
  private void Fun2()
  
{
   
int i = 0;
   String str 
= this.Text;
   
while (i<1000)
   
{
    i
++;
    
//this.Text = i.ToString();
    if (this.processEvent != null)
    
{
     
this.processEvent(i);
    }

    System.Threading.Thread.Sleep(
8);
   }
   
   TelMe();
   
this.Text = str;
  }


  
//异步委托可以也必须要一个参数,当然不想用就传一个null就可以了
  private void Fun(object obj)
  
{
   
int i = 0;
   String str 
= this.Text;
   
while (i<1000)
   
{
    i
++;
    
//this.Text = i.ToString();
    if (this.processEvent != null)
    
{
     
this.processEvent(i);
    }

    System.Threading.Thread.Sleep(
8);
   }
   
   TelMe();
   
this.Text = str;
  }


  
//不是回调,但是同一个类里写的,就可以直接调用了。
  private void TelMe()
  
{
   
this.processEvent -= new myProcessEventHandle(Form1_processEvent);
   button1.Enabled 
= true;
   button2.Enabled 
= true;
   MessageBox.Show(
"操作完成!");
  }


  
//事件方式通知主线程进度
  private void Form1_processEvent(int percent)
  
{
   
this.progressBar1.Value = percent;
   
this.Text = ((double)percent/10).ToString() + "%";
  }


  
private void Form1_Closed(object sender, System.EventArgs e)
  
{
   System.Environment.Exit(
0);//用于退出没有运行结束的线程
  }

 }

}



//以上代码在vs2003可以运行。以前写的例子。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值