C# this.Invoke()的作用与用法、不阻塞UI界面线程的延时函数

  • Post author:
  • Post category:其他

一、this.Invoke()的作用与用法、不阻塞UI界面线程的延时函数

Invoke()的作用是:在应用程序的主线程上执行指定的委托。一般应用:在辅助线程中修改UI线程( 主线程 )中对象的属性时,调用this.Invoke();

在多线程编程中,我们经常要在工作线程中去更新界面显示,而在多线程中直接调用界面控件的方法是错误 的做法,Invoke 和 BeginInvoke 就是为了解决这个问题而出现的,使你在多线程中安全的更新界面显示。

正确的做法是将工作线程中涉及更新界面的代码封装为一个方 法,通过 Invoke 或者 BeginInvoke 去调用,两 者的区别就是一个导致工作线程等待,而另外一个则不会。

//用法1:无参数,无返回值
Action action = () =>
  {
                          
      //刷新UI界面控件数据                      
  };
  this.Invoke(action);


//用法2:2个参数,无返回值
 void ShowColor(string filePath, List<string> colorPicFileName)
{

}
 Action<string, List<string>> action = ShowColor;
 this.Invoke(action, _colorFilePath, colorPicFileNames);

//用法3:无参数,无返回值,直接实例化
void ShowInputPanel()
{

}
this.Invoke(new Action(ShowInputPanel));

//用法4:无参数,无返回值
//lambda表达式(不需要定义函数名,直接执行函数体, =>左边()内也可以输入参数, =>右边输入函数体)
this.Invoke(new Action(() => _previewControl.ShowE(_currentDirection, value)));

//不阻塞UI界面线程的延时函数
    public static void DelayMs(int milliSecond)
    {
         int start = Environment.TickCount;
         while (Math.Abs(Environment.TickCount - start) < milliSecond)
         {
             Application.DoEvents();
         }
    }


版权声明:本文为xujianjun229原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。