is it safe to set an event handler (or delegate) AFTER an asynchronous method call in C#? For example, the following:
LoginOperation lo = WebContext.Current.Authentication.Login(new LoginParameters(UserName_Email.Text, UserPassword.Password));
lo.Completed += new EventHandler((object sender, EventArgs e) =>
{
if ((sender as LoginOperation).LoginSuccess)
{
//MessageBox.Show("Login Success");
this.DialogResult = true;
InitializeUserAccount(UserName_Email.Text);
}
else
{
MessageBox.Show("Login Failed");
}
});
In this example, I am setting the loginoperation event handler AFTER I make the asynchronous call. This always works but I don’t know if I have essentially setup a race condition? (and setting the handler always wins the race). OR…do asynchronous calls somehow dispatched after the current thread of execution has gone idle (or something like that)?
I do this for code readability. Just wondering if I am setting myself up here.
No, it’s not. Theoretically, if a context switch occurred after the
Logincall but before theCompletedevent is wired up, the login logic might complete before control returns to the original thread. Thus, the event handler may not be called.In this particular case, however, it’s likely you’re never seeing a problem because
Logintakes a relatively large amount of time to complete. Thus, it is extremely unlikely that it completes before the event handler is wired up. I’d classify as a ticking time bomb though.