1

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?

Luke Baulch
  • 3,626
  • 6
  • 36
  • 44

1 Answers1

1

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.

Community
  • 1
  • 1
ColinE
  • 68,894
  • 15
  • 164
  • 232