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);
                    }
                });
            }
     
        }
    }
  • 相关阅读:
    Unity Shader _Time
    常见纹理压缩格式
    U3D Transform组件
    java计算文件32位md5值
    Andoid 利用ndk-stack定位崩溃代码
    glsl计算sprite的亮度饱和度对比度
    Android项目文件结构
    Android Studio文件目录介绍
    Struts2配置dtd约束
    java系列--JSP的属性和内置对象
  • 原文地址:https://www.cnblogs.com/51net/p/3994538.html
Copyright © 2011-2022 走看看