Cleanest way to write retry logic?

前端 未结 29 2586
旧巷少年郎
旧巷少年郎 2020-11-22 03:01

Occasionally I have a need to retry an operation several times before giving up. My code is like:

int retries = 3;
while(true) {
  try {
    DoSomething();
         


        
29条回答
  •  别那么骄傲
    2020-11-22 03:22

    Here's an async/await version that aggregates exceptions and supports cancellation.

    /// 
    protected static async Task DoWithRetry( Func> action, CancellationToken cancelToken, int maxRetries = 3 )
    {
        var exceptions = new List();
    
        for ( int retries = 0; !cancelToken.IsCancellationRequested; retries++ )
            try {
                return await action().ConfigureAwait( false );
            } catch ( Exception ex ) {
                exceptions.Add( ex );
    
                if ( retries < maxRetries )
                    await Task.Delay( 500, cancelToken ).ConfigureAwait( false ); //ease up a bit
                else
                    throw new AggregateException( "Retry limit reached", exceptions );
            }
    
        exceptions.Add( new OperationCanceledException( cancelToken ) );
        throw new AggregateException( "Retry loop was canceled", exceptions );
    }
    

提交回复
热议问题