相關文章:

C# Delegates with Anonymous Methods(匿名方法)and Named Methods(具名方法)

 

框架如下

   1: private void button1_Click(object sender, EventArgs e)
   2: {
   3:     G_th = new System.Threading.Thread(   //新建一條線程
   4:         delegate()                        //使用匿名方法        
   5:         {
   6:  
   7:         });
   8: }

該執行緒要執行的內容為while-loop

利用while(true){}不斷進行計數器++, 當超過10000則歸零

   1: private void button1_Click(object sender, EventArgs e)
   2: {
   3:     G_th = new System.Threading.Thread(   //新建一條線程
   4:         delegate()                        //使用匿名方法        
   5:         {
   6:             int cnt = 0;                  //初始化計數器
   7:             while (true)                  //開始無限循環
   8:             {
   9:                 cnt = ++cnt > 10000 ? 0 : cnt;
  10:  
  11:             }
  12:         });
  13: }

如果想要將計數器顯示在人機介面上如下(錯誤示範)

   1: private void button1_Click(object sender, EventArgs e)
   2: {
   3:     G_th = new System.Threading.Thread(   //新建一條線程
   4:         delegate()                        //使用匿名方法        
   5:         {
   6:             int cnt = 0;                  //初始化計數器
   7:             while (true)                  //開始無限循環
   8:             {
   9:                 cnt = ++cnt > 10000 ? 0 : cnt;
  10:                 label1.Text = cnt.ToString();
  11:             }
  12:         });
  13:     G_th.Start();
  14: }

label.Text = cnt.ToString();這一行會跳出錯誤訊息

image

Usually I used to using a timer to access that global variable (cnt).

In fact there is a better way to do that by invoking an anonymous method.

// Invoke an anonymous method on the thread of the form.

this.Invoke( (MethodInvoker)

delegate

{

 

});

 

   1: private void button1_Click(object sender, EventArgs e)
   2:        {
   3:            G_th = new System.Threading.Thread(   //新建一條線程
   4:                delegate()                        //使用匿名方法        
   5:                {
   6:                    int cnt = 0;                  //初始化計數器
   7:                    while (true)                  //開始無限循環
   8:                    {
   9:                        cnt = ++cnt > 10000 ? 0 : cnt;
  10:                        this.Invoke(                //將程式碼交給主線程執行
  11:                            (MethodInvoker)delegate //使用匿名方法
  12:                        {
  13:                            label1.Text = cnt.ToString();
  14:                        });
  15:                    }
  16:                    System.Threading.Thread.Sleep(1000);
  17:                });
  18:            G_th.Start();
  19:        }
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()