【发布时间】:2008-10-10 20:51:50
【问题描述】:
我最近创建了这两个(不相关的)方法来替换我的 winforms 应用程序中的大量样板代码。据我所知,它们工作正常,但我需要一些保证/建议来确定是否存在我可能遗漏的一些问题。
(根据记忆)
static class SafeInvoker
{
//Utility to avoid boiler-plate InvokeRequired code
//Usage: SafeInvoker.Invoke(myCtrl, () => myCtrl.Enabled = false);
public static void Invoke(Control ctrl, Action cmd)
{
if (ctrl.InvokeRequired)
ctrl.BeginInvoke(new MethodInvoker(cmd));
else
cmd();
}
//Replaces OnMyEventRaised boiler-plate code
//Usage: SafeInvoker.RaiseEvent(this, MyEventRaised)
public static void RaiseEvent(object sender, EventHandler evnt)
{
var handler = evnt;
if (handler != null)
handler(sender, EventArgs.Empty);
}
}
编辑:查看相关问题here
更新
由于死锁问题(与this question 相关),我已从 Invoke 切换到 BeginInvoke(请参阅说明 here)。
另一个更新
关于第二个 sn-p,我越来越倾向于使用“空委托”模式,它通过直接使用空处理程序声明事件来“从源头”解决这个问题,如下所示:
event EventHandler MyEventRaised = delegate {};
【问题讨论】:
标签: c# coding-style