Question: I commonly employ a while loop that continues to try some operation until either the operation succeeds or a timeout has elapsed:

```
bool success = false
int elapsed = 0
while( ( !success ) && ( elapsed < 10000 ) )
{
     Thread.sleep( 1000 );
     elapsed += 1000;
     success = ... some operation ...     
}

```

I know there a couple of way to implement this, but the basic point is that I repeatedly try some operation with a sleep until success or I've slept too long in aggregate.

Is there a built-in .net class/method/etc to save me from re-writing this pattern all over the place? Perhaps input is an Func(of bool) and the timeout?

**Edit**  
Thanks to all who contributed. I opted for the sleep() approach because it was the least complicated and I'm totally anti-complexity =) Here's my (still needs to be tested) implimentation:

```
 public static bool RetryUntilSuccessOrTimeout( Func<bool> task , TimeSpan timeout , TimeSpan pause )
    {

        if ( pause.TotalMilliseconds < 0 )
        {
            throw new ArgumentException( "pause must be >= 0 milliseconds" );
        }
        var stopwatch = Stopwatch.StartNew();
        do
        {
            if ( task() ) { return true; }
            Thread.Sleep( ( int )pause.TotalMilliseconds );
        }
        while ( stopwatch.Elapsed < timeout );
        return false;
    }

```

Answer: 
The first solution is to use SpinWait

```
SpinWait.SpinUntil(() => LoopProcedure(), 1000);

```

The other solution is to use Task.Wait()

```
var task = Task.Run(() => LoopProcedure()); 
task.Wait(1000);

```

Wrap your loop into a procedure that return bool value

```
private bool LoopProcedure()
{
   bool success = false
   while( ( !success )
   {
      // do some stuff ...
   }
   return success;
}

```
You need to use [Thread.Join](http://msdn.microsoft.com/en-us/library/95hbf2ta.aspx). From MSDN,

> 
> Blocks the calling thread until a
>  thread terminates, while continuing to
>  perform standard COM and SendMessage
>  pumping.
> 
> 
> 

If you want to wait until a specified time elapses, then use the [Thread.Join (TimeSpan)](http://msdn.microsoft.com/en-us/library/23f7b1ct.aspx) method. .NET 3.0, 3.5, 4.0 only.

> 
> Blocks the calling thread until a
>  thread terminates or the **specified
>  time elapses**, while continuing to
>  perform standard COM and SendMessage
>  pumping.
> 
> 
> 

This tutorial on how to use [Threads in C#](http://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx) will help you.