// before retry clear connection
        private async Task disposeConnection()
        {
            if (currentConnection != null)
            {
                // close connection on error
                await tcpConnectionFactory.Release(currentConnection, true);

                currentConnection = null;
            }
        }
        //before retry clear connection
        private async Task onRetry(Exception ex, int attempt)
        {
            if (currentConnection != null)
            {
                //close connection on error
                await tcpConnectionFactory.Release(currentConnection, true);

                currentConnection = null;
            }
        }
 //get the policy
 private Policy getRetryPolicy()
 {
     return(Policy.Handle <T>()
            .RetryAsync(retries,
                        onRetryAsync: async(ex, i, context) =>
     {
         if (currentConnection != null)
         {
             //close connection on error
             await tcpConnectionFactory.Release(currentConnection, true);
             currentConnection = null;
         }
     }));
 }
Exemple #4
0
        /// <summary>
        ///     Execute and retry the given action until retry number of times.
        /// </summary>
        /// <param name="action">The action to retry with return value specifying whether caller should continue execution.</param>
        /// <param name="generator">The Tcp connection generator to be invoked to get new connection for retry.</param>
        /// <param name="initialConnection">Initial Tcp connection to use.</param>
        /// <returns>Returns the latest connection used and the latest exception if any.</returns>
        internal async Task <RetryResult> ExecuteAsync(Func <TcpServerConnection, Task <bool> > action,
                                                       Func <Task <TcpServerConnection> > generator, TcpServerConnection?initialConnection)
        {
            currentConnection = initialConnection;
            bool      @continue = true;
            Exception?exception = null;

            var attempts = retries;

            while (true)
            {
                // setup connection
                currentConnection ??= await generator();

                try
                {
                    @continue = await action(currentConnection);
                }
                catch (Exception ex)
                {
                    exception = ex;
                }

                attempts--;

                if (attempts < 0 || exception == null || !(exception is T))
                {
                    break;
                }

                exception = null;

                // before retry clear connection
                await tcpConnectionFactory.Release(currentConnection, true);

                currentConnection = null;
            }

            return(new RetryResult(currentConnection, exception, @continue));
        }