开发者

Method dispose functionality C#

Is there a way to dispose method variables without using try-finally block in C# 2010 (.Net 4)?

The story: I have few files handler methods. Each handler (method) can abort in the middle of execution. I like to dispose all method's object before exiting the method. The option to compose dispose method for each handler is not an option.

Thank you

This demonstrate the general idea: `public static class Comparison { private static bool CompareXmls(...) { //has 7 object to be disposed in 3 exit points acordding to 4 conditions

        //General method flow:

        //1. init part of the object

        //2. if(!<condition1>)
                //disposed objects
                //exit method

        //3. perform some actions

        //4. init some of the other objects

        //2. if(!<condition2>)
                //disposed objects
                //exit method

        //and so on...
    }

    private static bool CompareJpgs(...)
    {
        //has 12 object to be disposed in 10 exit points acordding to 4 conditions
    }

    private static bool CompareBitMaps(...)
    {
        //has 5 object to be disposed in 3 exit points acordding to 4 conditions
    }

 开发者_如何转开发   private static bool CompareTxts(...)
    {
        //has 12 object to be disposed in 10 exit points acordding to 4 conditions
    }
}`

I have another 7 comparison methods


using? Refer here for the full description on how and why to use http://msdn.microsoft.com/en-us/library/yh598w02(v=VS.100).aspx. A sample would be

using (MyDisposableType disposable1 = GetDisposable1(), disposable2 = GetDisposable2() /*,...*/)
{
    //your actions
}

after exiting from the using block, all disposable objects declared in its header will be disposed.

If your disposable objects are of different types, you can use nested usings:

using (MyDisposableType1 disposable1 = GetDisposable1())
{
    using (MyDisposableType2 disposable2 = GetDisposable2())
    {
        //more usings if needed, and then your actions
    }
}


I would put the method on an object that impiments idisposible and call this.dispose() in a finally block

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜