Using "using" with a method

29 ביוני 2008

תגיות: ,
3 תגובות

This is a coding technique I've learned today from looking at Rhino mocks Playback() method code.
It's a nice and smooth technique and I can think of several uses for it.

Consider the following code:

public static void DoSomething()

{

    TimerClass timer = new TimerClass();

 

    using (timer.CountTime())

    {

        string s = "hello world";

        for (int i = 0; i < 100000; i++)

        {

            int index = s.IndexOf("world");

        }

    }

}

This code will result in writing to the console: "Total time: 110ms".
How is it done?

public class TimerClass

{

    public IDisposable CountTime()

    {

        return new MyTimer();

    }

 

    private class MyTimer : IDisposable

    {

        int start;

 

        public MyTimer()

        {

            start = Environment.TickCount;

        }

 

        public void Dispose()

        {

            Console.WriteLine("Total ms: {0} ms", (Environment.TickCount – start));

        }

    }

}

The "secret" is returning an inner disposable class that will take care of what you need…

Hope you've been enlightened,
Shay.


Share this post : del.icio.us it! digg it! dotnetkicks it! technorati!

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים

3 תגובות

  1. Samuel Jack7 ביולי 2008 ב 11:35

    You can also use this technique for capturing and restoring state before and after doing some work, as I've shown here: http://blog.functionalfun.net/2008/05/misusing-idisposable-beyond-resource.html

    להגיב