查看文章
 
.net 3.5下用Lambda简化跨线程访问窗体控件,避免繁复的delegate,Invoke
2009-01-10 15:19
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();            
             });
         }
     }
}


类别:c#||添加到搜藏 |分享到i贴吧|浏览(1007)|评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
     

   
帮助中心 | 空间客服 | 投诉中心 | 空间协议
©2012 Baidu