zoukankan      html  css  js  c++  java
  • 跨线程的安全更新控件

    在你的工程中的扩展方法类中写下一个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);
                    }
                });
            }
     
        }
    }
  • 相关阅读:
    sqlserver中自定义函数+存储过程实现批量删除
    javascript的词法分析
    struts2 OGNL(Object-Graph Navigation Language) 井号,星号,百分号
    SimpleAdapter
    IntentService源码分析
    Service 的 onStartCommand(Intent, int, int) 返回值
    AppFog使用
    Looper分析。ThreadLocal有关
    HandlerThread分析
    form表单的enctype属性
  • 原文地址:https://www.cnblogs.com/51net/p/3994538.html
Copyright © 2011-2022 走看看