winform 多线程

 先上图:

 

 

说明,当单击button1时,线程休息10秒钟。但button2也可以继续响应。

 代码如下:

View Code
 1    public partial class Form3 : Form
 2     {
 3         public Form3()
 4         {
 5             InitializeComponent();
 6          
 7          
 8         }
 9         private void sleep()
10         {
11 
12             Thread.Sleep(10 * 1000); 
13             Console.WriteLine("fdfdf线程50");
14         }
15 
16         private void button1_Click(object sender, EventArgs e)
17         {
18             Action sleepActio = new Action(sleep);
19             sleepActio.BeginInvoke(nullnull);
20            
21         }
22 
23         private void button2_Click(object sender, EventArgs e)
24         {
25             Console.WriteLine("button2");
26         }
27         //既然这个WndProc是Win32中处理消息的方法的.Net版,那么我们应该在这里可以监视到所有用户操作的“消息”
28 
29      
30     }

 

 

 另一种异步回调的代码如下:

View Code
 1   public partial class Form3 : Form
 2     {
 3         public Form3()
 4         {
 5             InitializeComponent();
 6             Debug.Listeners.Add(new ConsoleTraceListener());
 7          
 8         }
 9         private int sleep()
10         {
11 
12             Thread.Sleep(10 * 1000); 
13             Console.WriteLine("fdfdf线程50");
14             return 10;
15         }
16 
17         private void button1_Click(object sender, EventArgs e)
18         {
19             int ret = 0;
20             Func<int> longTimeAction = new Func<int>(sleep);
21 
22        //这里使用了一个lambda表达式,省了不少力啊
23 
24         IAsyncResult asynResult = longTimeAction.BeginInvoke((result) => {
25 
26             ret = longTimeAction.EndInvoke(result);
27             MessageBox.Show(ret.ToString());
28 
29         }, null);
30             
31        
32         }
33 
34         private void button2_Click(object sender, EventArgs e)
35         {
36             Console.WriteLine("button2");
37         }
38         //既然这个WndProc是Win32中处理消息的方法的.Net版,那么我们应该在这里可以监视到所有用户操作的“消息”
39 
40        protected override void WndProc(ref Message m)
41       {
42         Debug.WriteLine(m.Msg.ToString());
43          base.WndProc(ref m);
44      }
45     }

 

 

参考: winform多线程

posted on 2011-09-15 16:29  wtq  阅读(931)  评论(0编辑  收藏  举报