vendredi 24 décembre 2010

How to implement a generic “waiting for” function with C#

In order to avoid repeating myself in the code of my team’s project where we need several times to wait for something to happen such as waiting for a file, I learned how to use the type “Func”.

Here is how was the code before the refactoring :

public static bool WaitForFile(string filePath, int timeOutMs)
{
    var fileFound = false;
    var timeElapsed = false;

    var startTime = DateTime.Now;
    DateTime currentTime;
    while (!fileFound && !timeElapsed)
    {
        currentTime = DateTime.Now;
        TimeSpan span = currentTime.Subtract(startTime);

        timeElapsed = span.TotalMilliseconds > timeOutMs;

        fileFound = System.IO.File.Exists(filePath);
        System.Threading.Thread.Sleep(1000);
    }
    return fileFound;

}

And here is the new generic implementation :

public static bool WaitForSynchrone(Func<bool> function, int timeOutMs)
{
    var actionReturnedTrue = false;
    var timeElapsed = false; var startTime = DateTime.Now;
    DateTime currentTime;
    while (!actionReturnedTrue && !timeElapsed)
    {
        currentTime = DateTime.Now;
        TimeSpan span = currentTime.Subtract(startTime);
        timeElapsed = span.TotalMilliseconds > timeOutMs;
        actionReturnedTrue = function();
        System.Threading.Thread.Sleep(1000);
    }
    return actionReturnedTrue;
}

public void WaitFile()
{
    WaitForSynchrone(() => File.Exists("C:\myfile.txt"), 10000);
}

So, now, we have a new function  WaitForSynchrone that take 2 arguments :

    - Func<bool> function : A function that returns a boolean

    - int timeOutMs : A timeout to prevent freezing !!

And we use it thanks to lambda expression for the first argument :

    - () => File.Exists("C:\myfile.txt")   : This is a function that takes no arguments and returns and boolean according to the left part of the expression

So now, we can use WaitForSynchrone for many other purpose instead of violating the DRY principle = ‘Do Not Repeat yourself ‘.


Share/Bookmark

Aucun commentaire: