【发布时间】:2014-03-27 07:35:30
【问题描述】:
我有一个事件及其方法声明如下,它是一个 Windows 窗体登录控件的身份验证事件:
public event EventHandler<AuthenticateEventArgs> Authenticate;
protected void OnAuthenticate(AuthenticateEventArgs e)
{
EventHandler<AuthenticateEventArgs> handler = Authenticate;
if (handler != null)
{
handler(this, e);
}
if (e.Authenticated)
{
OnLoggedIn(new EventArgs());
}
else
{
OnLoggedError(new EventArgs());
}
}
点击按钮时会引发该事件,现在假设在其他一些项目中有该事件的订阅者,如下所示:
this.loginControl1.Authenticate += loginControl1_Authenticate;
this.loginControl1.Authenticate += delegate(object o, AuthenticateEventArgs ea)
{
System.Threading.Thread.Sleep(2000);
ea.Authenticated = false;
};
this.loginControl1.Authenticate += delegate(object o, AuthenticateEventArgs ea)
{
System.Threading.Thread.Sleep(2000);
ea.Authenticated = true;
};
this.loginControl1.Authenticate += delegate(object o, AuthenticateEventArgs ea)
{
System.Threading.Thread.Sleep(2000);
ea.Authenticated = false;
};
System.Threading.Thread.Sleep(2000); 只是对需要一些时间的某些过程的模拟。问题是最后一个订阅者在 OnAuthenticate 方法中执行 If 条件并引发另一个事件,而之前的订阅者没有。代码完美适用于一位订阅者。这种情况下问题出在哪里?
【问题讨论】:
-
会发生什么?总是
Authenticated是假的? -
是的。 Authenticated 值将始终是最后一个订阅者中的值,无论它是 true 还是 false。
-
您希望
OnLoggedIn()函数执行一次,OnLoggedError执行两次,用给定的例子?这就是你想要的吗? -
是的,这就是我想要的。
-
OnLoggedIn()和OnLoggedError()的参数是什么。你需要AuthenticationArgs吗?
标签: c# events user-controls delegates event-handling