Luke Baulch
Luke Baulch

Reputation: 3656

Is there a way to add and detach an event handler without loosing scope?

Working with asynchronous classes, often I find that I am always having to store state in fields so that I have access to them in the completed method. Ideally, I'd like to avoid having to store state in fields as this means I need to worry about multiple calls being made and their affect on the field data.

I wrote this block of code which could work, although Resharper gives me an 'access to modified disclosure' warning.

public void Test(Action<Result> result)
{
    var myClass = new MyClass();
    EventHandler eventHandler = null;
    eventHandler = (s, e) =>
                        {
                            var mc = (MyClass) s;
                            mc.Completed -= eventHandler;
                            result(mc.Result);
                        };
    myClass.Completed += eventHandler;
    myClass.Run();
}

Is there a problem with this block of code and if not, is there a better way to do this without creating fields to store data and ensure that some level of scope still exists?

Upvotes: 1

Views: 83

Answers (1)

ColinE
ColinE

Reputation: 70142

Your usage of an anonymous delegate in this context is absolutely fine. For a discussion on the specific ReSharper warning, see the following question which discusses it in detail:

Access to Modified Closure

I use the pattern you have illustrated quite often in WPF / Silverlight / WP7 application when you want to execute some code just once when the UI is first loaded or rendered.

Upvotes: 1

Related Questions