开发者

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

开发者 https://www.devze.com 2023-04-07 16:17 出处:网络
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 stat

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 bett开发者_Python百科er way to do this without creating fields to store data and ensure that some level of scope still exists?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号