现在的位置: 首页 > 综合 > 正文

线程 和异步委托

2013年10月12日 ⁄ 综合 ⁄ 共 3996字 ⁄ 字号 评论关闭
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
++

抱歉!评论已关闭.