Car*_*los 4 .net c# attributes syntactic-sugar winforms
在我的GUI代码中,我经常写这样的东西:
private void SecondTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (progressBar1.InvokeRequired)
{
progressBar1.BeginInvoke(new ElapsedEventHandler(SecondTimer_Elapsed), new[] {sender, e});
return;
}
//Code goes here
}
Run Code Online (Sandbox Code Playgroud)
当然,如果应用程序是多线程的,这是必要的,因为我们需要编组最初创建控件的线程.问题是,编写委托并将参数放入数组可能会很繁琐,并且它会在每个这样的事件处理程序的顶部占用空间.是否有一个属性或类似的东西将为您替换此代码?基本上是一个标签,上面写着"如果你在错误的线程上,请在GUI线程上再次使用相同的args给我打电话."
Jon*_*eet 13
我不知道任何类似的东西,但这可能是一个有用的扩展方法:
public static class Extensions
{
public static void Execute(this ISynchronizeInvoke invoker,
MethodInvoker action)
{
if (invoker.InvokeRequired)
{
invoker.BeginInvoke(action);
}
else
{
action();
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在这只适用于无参数的委托,当然......但是lambda表达式不一定是个问题:
progressBar1.Execute(() => SecondTimer_Elapsed(sender, e));
Run Code Online (Sandbox Code Playgroud)
这具有以下优点:
MethodInvoker
我相信,其执行效率略高于其他代表