If I write something like
myDataModel.ContentLoaded += (o,e) => { DoSomething(); }
When (if ever) is that anonymous delegate removed from the event?
As a quick example, I could write this program
class Program
{
public event EventHandler<EventArgs> MyEvent = delegate { };
static void Main(string[] args)
{
Program p = new Program();
while(true)
{
p.MyEvent += (o, e) => Console.WriteLine("Hello!");
Console.ReadLine();
p.Foo();
}
}
void Foo()
{
MyEvent(this, EventArgs.Empty);
}
}
And the output as I press 'Enter' repeatedly is
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
...and so forth. I could add the line
p.MyEvent -= (o, e) => Console.WriteLine("Hello!");
after p.Foo()
but of course it has no effect because I'm removing an entirely different anonymous delegate.
So what's the deal with this? Is there any way of removing these anonymous delegates at all? What are the implications for, say, an asynchronous Silverlight application where I'm pulling data using expressions like
_myDataContext.Load(myQuery, loadOperation =>
{
// do stuff with the data here
}, null);
? I assume that these kinds of callbacks aren't implemented using events, but of course it's impossible(?) to tell.
Are anonymous delegates dangerous if not carefully accounted for?