
李的方法可以进一步简化
public static void InvokeIfRequired(this Control control, MethodInvoker action){ // See Update 2 for edits Mike de Klerk suggests to insert here. if (control.InvokeRequired) { control.Invoke(action); } else { action(); }}可以这样称呼
richEditControl1.InvokeIfRequired(() =>{ // Do anything you want with the control here richEditControl1.RtfText = value; RtfHelpers.AddMissingStyles(richEditControl1);});无需将控件作为参数传递给委托。C#自动创建一个闭包。
更新 :
根据其他几个海报
Control可以概括为
ISynchronizeInvoke:
public static void InvokeIfRequired(this ISynchronizeInvoke obj, MethodInvoker action){ if (obj.InvokeRequired) { var args = new object[0]; obj.Invoke(action, args); } else { action(); }}DonBoitnott指出,与接口不同,
Control该
ISynchronizeInvoke接口需要该
Invoke方法的对象数组作为的参数列表
action。
更新2
Mike de Klerk建议进行的编辑(有关插入点,请参见第一个代码段中的注释):
// When the form, thus the control, isn't visible yet, InvokeRequired returns false,// resulting still in a cross-thread exception.while (!control.Visible){ System.Threading.Thread.Sleep(50);}有关此建议的担忧,请参见下面的ToolmakerSteve的评论。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)