I have a challenge in my C# .NET application that I can’t figure out how to resolve. I have an object that has a method called “Load”. If the object is loaded successfully, one event is fired. If the object fails to load, another event is fired. This entity is defined as follows:
public class MyEntity
{
public event EventHandler Load_Succeeded;
public event EventHandler Load_Failed;
public void Load()
{
/*
Asynchronously load the entity code here.
*/
}
private void Load_Completed(IAsyncResult result)
{
// Fire Load_Succeeded or Load_Failed
}
}
Now, if the Load fails, I store the object in isolated storage to attempt to load it later. When I attempt to load the object later, I have the following code:
MyEntity myEntity = GetFromIsolatedStorage();
myEntity.Load_Failed -= new EventHandler(myEntity_Load_Failed);
myEntity.Load_Failed += new EventHandler(myEntity_Load_Failed);
myEntity.Load_Succeeded -= new EventHandler(myEntity_Load_Succeeded);
myEntity.Load_Succeeded += new EventHandler(myEntity_Load_Succeeded);
myEntity.Load();
The odd part is, when I run the Load code via the entity loaded from isolated storage, the original Load_Failed and Load_Succeeded event handlers are executed. Even though I am using “-=”. What am i doing wrong? How do I clear all of the event handlers on an object so that I can essentially reset them?
Thank you!
You can remove an eventHandler only on the object that defines the event. That means you can use this:
And then just call