跨线程的安全更新控件

在你的工程中的扩展方法类中写下一个SafeCall方法:
using System;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public static class Extensions
    {
        public static void SafeCall(this Control ctrl, Action callback)
        {
            if (ctrl.InvokeRequired)
                ctrl.Invoke(callback);
            else
                callback();
        }
    }
}
它只是把你要保护起来的代码作为一个回调而已。然后任何需要保护一些代码的地方都可以这样调用:
using System;
using System.Threading;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(h =>
            {
                for (var i = 0; i < 10000000; i++)
                {
                    label1.SafeCall(() =>
                    {
                        label1.Text = i.ToString();
                    });
                    Thread.Sleep(100);
                }
            });
        }
 
    }
}
当然,使用lamda是我的一个“坏毛病”。其实这里完全可以使用传统的匿名委托写法:

using System;
using System.Threading;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(h =>
            {
                for (var i = 0; i < 10000000; i++)
                {
                    label1.SafeCall(delegate()
                    {
                        label1.Text = i.ToString();
                    });
                    Thread.Sleep(100);
                }
            });
        }
 
    }
}

 

posted @ 2014-09-26 11:43  跟着阿笨一起玩.NET  阅读(357)  评论(0编辑  收藏  举报