Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Extensions: Action.Delay

0.00/5 (No votes)
20 Aug 2012 1  
My series of posts on extension methods in .NET: Action.Delay

Introduction

Welcome to my series of posts on extension methods in .NET. I'll be sharing my most useful extensions to you all. Both C# and VB.NET provide support for extension methods. In case you're not aware about extensions in .NET, spend just 5 minutes, they're very nice. Extension methods are just like ordinary methods in .NET, but they stick to the type you make them for without inheriting that type or re-defining it with your extension. In other words, they act like they are member of type but actually are defined somewhere else. These are static methods but special ones. They've scope of namespace level. So, if you defined extensions in namespace Abc, you can use them by writing using Abc;

Like if you wanted to check whether an int is even or not, then you do something like this:

int i = 2;
if(i % 2 == 0)
{
    // Even ...
}

Ever wondered that if you could do something like this:

int i = 2;
if(i.IsEven())
{
    // Even ...
}

Or if you wanted to count the number of words of a string, then you do something like this:

string s = "Hello world";
int count = s.Split(' ').Length;

Ever wondered that if you could do something like this:

string s = "Hello world";
int count = s.GetTotalWords();

There are many examples, the above ones are very simple ones and not a good reason to use extensions. But remember System.Linq which you use mostly, of almost all the methods are extensions .Take, .Where, .Aggregate, ...

How Do We Define a Method as an Extension?

Firstly, you must note that all extension methods are static, and always defined in a static class.

We go like this:

namespace Extensions
{      
    public static class MyExtensions
    {
        public static bool IsEven(this int i)
        {
            return i % 2 == 0;
        }

        public static int GetTotalWords(this string s)
        {
            return s.Split(' ').Length;
        }
    }
}

Now, how to use?

using MyExtensions;

public class Program
{
    void Main()
    {
        string s = "Hello World";
        int i = 12498;
        Console.WriteLine(i + " is even = " + i.IsEven());
        Console.WriteLine(s + " is having " + s.GetTotalWords() + " words"); 
    }
}

Here's what we get:

12498 is even = true
Hello World is having 2 words

Action.Delay

/// <summary>
/// Delays the specified action for specified time (in ms).
/// </summary>
/// <param name="method">The action.</param>
/// <param name="delay">The delay time in ms.</param>
public static void Delay(this Action method, int delay, bool usingdispatcher)
{
    if(usingdispatcher)
    {
        DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Background);
        timer.Interval = TimeSpan.FromMilliseconds(delay);
        timer.Tick += ((d, e) =>
        {
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, method);
            timer.Stop();
            timer = null;
        });
        timer.Start();
    }
    else
    {
        Timer timer = null;
        timer = new Timer((c) =>
        {
            method.Invoke();
            timer.Dispose();
        }, null, delay, Timeout.Infinite);
    }
}

The Action.Delay extension is simple, it works just like setTimeout function in JavaScript. All it does is that it delays the method for given time. It's very useful especially in WPF animations, or if you want to call a method after sometime. I'll cover usage of this extension along with the next extension, stay tuned till then.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here