Home
Manage Your Code
Snippet: Wait for a action to succeed (C#)
Title: Wait for a action to succeed Language: C#
Description: Simple wait routine for a particular even to succeed Views: 453
Author: Stephen Smith Date Added: 6/23/2012
Copy Code  
1private bool WaitForSuccess(Func<bool> action, int millsecondTimeout = 2000)
2{
3    var start = DateTime.Now;
4    while ((DateTime.Now - start).TotalMilliseconds <= millsecondTimeout)
5    {
6        if (action()) return true;
7        Task.Delay(1); // or Thread.Sleep(1);

8    }
9    return false;
10}
Usage
if (close)
    if (!WaitForSuccess(() => _connection.State == ConnectionState.Closed))
        Trace.TraceWarning("The connection {0} close command timed-out!", _connection.ConnectionString);
Notes
Make sure the success action is accomplished on a separate thread (obviously)! C# 5.0 has a Task.Delay that would be better to use than thread.sleep