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 startTime = DateTime.Now; timeElapsed = span.TotalMilliseconds > timeOutMs; fileFound = System.IO.File.Exists(filePath); } |
And here is the new generic implementation :
public static bool WaitForSynchrone(Func<bool> function, int timeOutMs) public void WaitFile() |
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 ‘.
Aucun commentaire:
Enregistrer un commentaire