当一个方法的执行时间未知时,我们要在此方法执行完成后回调另外一个处理函数时,这段代码就有用处了

  1using System;
  2using System.Drawing;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Windows.Forms;
  6using System.Data;
  7namespace DelegateAndAsync
  8{
  9 /// <summary>
 10 /// Form1 的摘要说明。
 11 /// </summary>

 12 public class frmMain : System.Windows.Forms.Form
 13 {
 14
 15  public delegate DateTime WorkHandler(int sleepMillisecond);
 16
 17  private System.Windows.Forms.Button CmdStart;
 18  private System.Windows.Forms.RichTextBox RT001;
 19  private System.Windows.Forms.ProgressBar PB001;
 20  /// <summary>
 21  /// 必需的设计器变量。
 22  /// </summary>

 23  private System.ComponentModel.Container components = null;
 24
 25  public frmMain()
 26  {
 27   //
 28   // Windows 窗体设计器支持所必需的
 29   //
 30   InitializeComponent();
 31
 32   //
 33   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
 34   //
 35  }

 36
 37  /// <summary>
 38  /// 清理所有正在使用的资源。
 39  /// </summary>

 40  protected override void Dispose( bool disposing )
 41  {
 42   if( disposing )
 43   {
 44    if (components != null
 45    {
 46     components.Dispose();
 47    }

 48   }

 49   base.Dispose( disposing );
 50  }

 51
 52  Windows 窗体设计器生成的代码
100
101  /// <summary>
102  /// 应用程序的主入口点。
103  /// </summary>

104  [STAThread]
105  static void Main() 
106  {
107   Application.Run(new frmMain());
108  }

109
110  private void CmdStart_Click(object sender, System.EventArgs e)
111  {
112   MessageBox.Show("Start");
113   WorkHandler wHandle = new WorkHandler(this.StartWork);
114   wHandle.BeginInvoke(10000,new AsyncCallback(this.CompleteWork),wHandle);
115   
116  }

117
118  /// <summary>
119  /// 
120  /// </summary>
121  /// <param name="sleepMillisecond"></param>
122  /// <returns></returns>

123  private DateTime StartWork(int sleepMillisecond)
124  {
125   this.CmdStart.Enabled = false;
126   int val = 0;
127   while(true)
128   {
129    val += 10/(sleepMillisecond/1000);
130    System.Threading.Thread.Sleep(1000/(sleepMillisecond/1000));
131    this.PB001.Value = val;
132    if(val == 100 || val > 100 )
133     break;
134
135   }

136   return DateTime.Now;
137  
138  }

139
140  /// <summary>
141  /// 当StartWork完成后该做的任务
142  /// </summary>
143  /// <param name="ar"></param>

144  private void CompleteWork(IAsyncResult ar)
145  {
146   try
147   {
148    WorkHandler WH=(WorkHandler)ar.AsyncState;
149    DateTime dt = WH.EndInvoke(ar);   
150    MessageBox.Show(this,dt.ToString());
151    this.CmdStart.Enabled = true;
152   }

153   catch(Exception e)
154   {
155    Console.Write(e);
156   }

157  }

158
159  private void CompleteWork()
160  {
161   
162  }

163
164 }

165}

166
167
Posted on 2007-01-16 10:54  黑袍  阅读(516)  评论(1)    收藏  举报