Пример #1
0
        private static Task BackoffAsync(RetryContext context)
        {
            TimeSpan delay = TimeSpan.FromMilliseconds(10 * context.Iteration);

            Log("Backing off for {0:0.000} seconds.", delay.TotalSeconds);
            return(Task.Delay(delay));
        }
Пример #2
0
        private static async Task ReadFileAsync(RetryContext context)
        {
            try
            {
                using (FileStream stream = new FileStream("test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 256, true))
                {
                    byte[] buffer    = new byte[4];
                    int    bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);

                    if (bytesRead == buffer.Length)
                    {
                        string text = Encoding.ASCII.GetString(buffer);
                        Log("ReadFileAsync read '{0}'", text);
                        context.Add("Text", text);
                    }
                    else
                    {
                        Log("ReadFileAsync read only {0} bytes.", bytesRead);
                    }
                }
            }
            catch (Exception e)
            {
                Log("ReadFileAsync error: {0}: {1}", e.GetType().Name, e.Message);
                throw;
            }
        }
Пример #3
0
        public async Task <RetryContext> ExecuteAsync()
        {
            RetryContext context     = new RetryContext();
            bool         shouldRetry = false;
            TimeSpan     startTime   = this.Timer.Elapsed;

            do
            {
                try
                {
                    if (shouldRetry)
                    {
                        await this.BeforeRetry(context);
                    }

                    context.Exception   = null;
                    context.ElapsedTime = this.Timer.Elapsed - startTime;
                    await this.func(context);
                }
                catch (Exception e)
                {
                    context.Exception = new AggregateException(e);
                }

                context.ElapsedTime = this.Timer.Elapsed - startTime;
                context.Succeeded   = this.Succeeded(context);
                shouldRetry         = this.ShouldRetry(context);
                ++context.Iteration;
            }while (!context.Succeeded && shouldRetry);

            return(context);
        }
Пример #4
0
        public static async Task AddAsync <TResult>(this RetryContext context, string name, Task <TResult> task)
        {
            TResult result = await task;

            context.Add(name, result);
        }