zoukankan      html  css  js  c++  java
  • 控件的invoke和beginInvoke方法

    System.Windows.Forms.Timer 的timer是在主线程上执行的,因此在timer的tick事件中操作界面上的控件不会发生线程的安全性检测。

    Control的invoke和begininvoke方法的比较:

     invoke方法:使用Invoke完成一个委托方法的封送,就类似于使用SendMessage方法来给界面线程发送消息,是一个同步方法。

    复制代码
    private delegate void InvokeDelegate();
    
    private void InvokeMethod()
    
    {    //C代码段 }
    
    private void butInvoke_Click(object sender, EventArgs e)
    
    {   
    
     //A代码段.......   
    
     this.Invoke(new InvokeDelegate(InvokeMethod));  
    
      //B代码段......
    
    }
    复制代码

    invoke执行的顺序是A->C->B

    beginInvoke异步方法。

    复制代码
    Control的BeginInvoke private delegate void BeginInvokeDelegate();
    
     private void BeginInvokeMethod()
    
    {   
    
    //C代码段
    
    }
    
     private void butBeginInvoke_Click(object sender, EventArgs e)
    
    {   
    
     //A代码段.......   
    
     this.BeginInvoke(new BeginInvokeDelegate(BeginInvokeMethod));   
    
     //B代码段......
    
    }
    复制代码

    begininvoke执行的顺序是A->B->C

    下面列出几种control的invoke方法使用:

    1) Action的lambda方法的使用

    Control.invoke(new Action(()=>{.....;}));

    复制代码
      new Thread(() =>
                {
                    while (true)
                    {
                        label1.BeginInvoke(new MethodInvoker(() => { label1.Text = System.DateTime.Now.ToString(); }));
                        Thread.Sleep(1000);
                    }
                }) { IsBackground = true }.Start();
    复制代码

    2)实例委托

    复制代码
    private delegate void ChangeTxt();
         void time_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
            {
                ChangeTxt changetxtDelegate=new ChangeTxt(change);
                textBox1.Invoke(changetxtDelegate);
    //或者直接textBox1.Invoke(new ChangeTxt(change));

    }

    private void change() { textBox1.Text = (a++).ToString(); }
    复制代码

    3)传参数

    复制代码
     private delegate void showtest(string text);
     private void run()
            {
                showtest st = new showtest(show);
                for (int i = 0; i < 100000; i++)
                {
                    textBox1.Invoke(st, i.ToString());
                }
            }
    void show(string test)
            {
                textBox1.Text = test;
            }
  • 相关阅读:
    在某个点上弹出层
    根据表名、过程名、视图名查找对应的数据库
    js时间转换nan问题 兼容浏览器
    过滤html标记 以及 返回顶部
    自定义控件 加入include 报错 问题
    在有索引视图的表上新增、修改、删除 报错 set ARITHABORT 选项不对
    访微博代码
    兼容问题 链接不跳转
    js上下滚动代码
    onload问题
  • 原文地址:https://www.cnblogs.com/wwwbdabc/p/11653295.html
Copyright © 2011-2022 走看看