Click here to Skip to main content
15,890,186 members
Articles / Programming Languages / C#

Extensions: Action.Delay

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
20 Aug 2012GPL32 min read 11.2K   8   8
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:

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

Ever wondered that if you could do something like this:

C#
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:

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

Ever wondered that if you could do something like this:

C#
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:

C#
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?

C#
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

C#
/// <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, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Student
India India

Comments and Discussions

 
GeneralMy vote of 5 Pin
dave.dolan24-Aug-12 9:50
dave.dolan24-Aug-12 9:50 
cool way to encapsulate this! I didn't even know the dispatch timer existed.
GeneralMy vote of 5 Pin
ericpxz20-Aug-12 6:26
ericpxz20-Aug-12 6:26 
Questionwhy not System.Threading.Thread.Sleep(); Pin
ericpxz20-Aug-12 5:40
ericpxz20-Aug-12 5:40 
AnswerRe: why not System.Threading.Thread.Sleep(); Pin
Code098720-Aug-12 5:48
Code098720-Aug-12 5:48 
GeneralRe: why not System.Threading.Thread.Sleep(); Pin
ericpxz20-Aug-12 6:10
ericpxz20-Aug-12 6:10 
GeneralRe: why not System.Threading.Thread.Sleep(); Pin
ericpxz20-Aug-12 6:25
ericpxz20-Aug-12 6:25 
GeneralRe: why not System.Threading.Thread.Sleep(); Pin
Code098720-Aug-12 6:43
Code098720-Aug-12 6:43 
GeneralRe: why not System.Threading.Thread.Sleep(); Pin
ericpxz20-Aug-12 13:37
ericpxz20-Aug-12 13:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.