.net 3.5下用Lambda简化跨线程访问窗体控件,避免繁复的delegate,Invoke

原文:http://hi.baidu.com/guigangsky/blog/item/dc831f126d542a56f919b828.html

1,错误的代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
         }

         private string blog="http://www.dc9.cn/";


         private void Form1_Load(object sender, EventArgs e)
         {
             new System.Threading.Thread(ShowTime).Start();
         }

         private void ShowTime()
         {
             textBox1.Text = DateTime.Now.ToString();
         }
     }
}


会看到Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.的错误

2,增加一个Public static 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace WindowsFormsApplication5
{
     public static class ControlExtention
     {
         public delegate void InvokeHandler();

         public static void SafeInvoke(this Control control, InvokeHandler handler)
         {
             if (control.InvokeRequired)
             {
                 control.Invoke(handler);
             }
             else
             {
                 handler();
             }
         }
     }
}


3,build

4,这样写就好啦

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
         }
         private string s="http://www.dc9.cn/";

         private void Form1_Load(object sender, EventArgs e)
         {
             new System.Threading.Thread(ShowTime).Start();
         }

         private void ShowTime()
         {
             this.SafeInvoke(() => {
                 textBox1.Text = DateTime.Now.ToString();            
             });
         }
     }
}

 

posted @ 2009-12-30 17:15  冰封的心  阅读(214)  评论(0编辑  收藏  举报