本文整理汇总了C#中RetryPolicy.ExecuteAsync方法的典型用法代码示例。如果您正苦于以下问题:C# RetryPolicy.ExecuteAsync方法的具体用法?C# RetryPolicy.ExecuteAsync怎么用?C# RetryPolicy.ExecuteAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RetryPolicy
的用法示例。
在下文中一共展示了RetryPolicy.ExecuteAsync方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Insert
public static async Task Insert(CloudTable table)
{
CustomerEntity customer1 = new CustomerEntity("Harp", "Walters")
{
Email = "[email protected]",
PhoneNumber = "425-555-0101"
};
CustomerEntity customer2 = new CustomerEntity("Harp", "Ben")
{
Email = "[email protected]",
PhoneNumber = "425-555-0102"
};
TableBatchOperation batchOperation = new TableBatchOperation();
// Create the TableOperation object that inserts the customer entity.
TableOperation insertOperation = TableOperation.Insert(customer1);
batchOperation.Insert(customer1);
batchOperation.Insert(customer2);
// Execute the insert operation.
Incremental retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2));
ExponentialBackoff retryStrategy2=new ExponentialBackoff(5,TimeSpan.FromSeconds(1),TimeSpan.FromSeconds(5),TimeSpan.FromSeconds(2));
TimeSpan back = TimeSpan.FromSeconds(31);
// Define your retry policy using the retry strategy and the Azure storage
// transient fault detection strategy.
RetryPolicy<StorageTransientErrorDetectionStrategy> retryPolicy =
new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);
RetryPolicy<StorageTransientErrorDetectionStrategy> r =
new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy2);
// Receive notifications about retries.
retryPolicy.Retrying += (sender, args) =>
{
Console.WriteLine("Information");
// Log details of the retry.
var msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}",
args.CurrentRetryCount, args.Delay, args.LastException);
Console.WriteLine(msg, "Information");
};
try
{
// Do some work that may result in a transient fault.
await retryPolicy.ExecuteAsync(
() => table.ExecuteBatchAsync(batchOperation));
}
catch (Exception e)
{
var z = e;
}
Console.ReadLine();
/* // Create a new customer entity.
CustomerEntity customer1 = new CustomerEntity("Harp", "Walters")
{
Email = "[email protected]",
PhoneNumber = "425-555-0101"
};
CustomerEntity customer2 = new CustomerEntity("Harp", "Ben")
{
Email = "[email protected]",
PhoneNumber = "425-555-0102"
};
TableBatchOperation batchOperation = new TableBatchOperation();
// Create the TableOperation object that inserts the customer entity.
TableOperation insertOperation = TableOperation.Insert(customer1);
batchOperation.Insert(customer1);
batchOperation.Insert(customer2);
// Execute the insert operation.
try
{
IList<TableResult> z = await table.ExecuteBatchAsync(batchOperation);
foreach (var i in z)
{
CustomerEntity y = (CustomerEntity)i.Result;
Console.WriteLine(y.PartitionKey);
}
var x = z;
}
catch (StorageException e)
{
var z = e.RequestInformation.HttpStatusCode;
var zz = 3;
}*/
}
示例2: Throws_WhenExceptionIsNotRetryable
public static void Throws_WhenExceptionIsNotRetryable()
{
var fake = Substitute.For<IFake>();
var ex = new Exception();
fake.DoSomething().ThrowsTask(ex);
fake.IsRetryable(Arg.Any<int>(), ex).Returns(false);
var logger = Substitute.For<ILog>();
var delay = Substitute.For<Delay>();
var retryHandler = new RetryPolicy(logger, 100, 10, delay);
var actualEx = Record.Exception(() => retryHandler.ExecuteAsync(fake.DoSomething, fake.IsRetryable).GetAwaiter().GetResult());
Assert.Equal(ex, actualEx);
}
示例3: DoesNotRetry
public static async Task DoesNotRetry()
{
var fake = Substitute.For<IFake>();
fake.DoSomething().ReturnsTask(0);
fake.IsRetryable(1337, null).Returns(true);
fake.IsRetryable(0, null).Returns(false);
var logger = Substitute.For<ILog>();
var delay = Substitute.For<Delay>();
var retryHandler = new RetryPolicy(logger, 100, 10, delay);
var result = await retryHandler.ExecuteAsync(fake.DoSomething, fake.IsRetryable);
Assert.Equal(0, result);
fake.Received(1, x => x.DoSomething());
}
示例4: StartAsync
protected override async Task StartAsync()
{
InfoLogging(string.Format("{0} - Processing", SubscriptionName));
_subClient = await _clientFactory.CreateSubscriptionClientAsync(TopicName, SubscriptionName).ConfigureAwait(false);
_retryStrategy = CreateRetryPolicy(MessageRepostMaxCount);
var stopWatch = new Stopwatch();
while (!Token.IsCancellationRequested)
{
var message = await _subClient.ReceiveAsync(new TimeSpan(0, 0, 10)).ConfigureAwait(false);
if (message == null) continue;
var messageBody = message.GetBody<string>();
if (String.IsNullOrEmpty(messageBody)) continue;
var messageId = message.MessageId;
message.Complete();
DebugLogging(string.Format("{0} - Received new message", SubscriptionName), messageId);
var failed = false;
stopWatch.Restart();
try
{
await _retryStrategy.ExecuteAsync(() =>
Do(messageBody), Token).ConfigureAwait(false);
stopWatch.Stop();
var timeSpan = stopWatch.Elapsed;
DebugLogging(string.Format("{0} - Processed message",
SubscriptionName), messageId,
timeSpan.TotalSeconds);
}
catch (Exception exception)
{
ErrorLogging("Message processing failed after retry, posting as failed message.", messageId,
exception);
failed = true;
}
if (failed)
await HandleFailedMessageAsync(messageBody).ConfigureAwait(false);
}
}
示例5: Retries_WhenShouldRetry
public static async Task Retries_WhenShouldRetry()
{
var fake = Substitute.For<IFake>();
fake.DoSomething().ReturnsTask(1337, 1337, 1337, 0);
fake.IsRetryable(1337, null).Returns(true);
fake.IsRetryable(0, null).Returns(false);
var logger = Substitute.For<ILog>();
var delay = Substitute.For<Delay>();
var retryHandler = new RetryPolicy(logger, 100, 10, delay);
await retryHandler.ExecuteAsync(fake.DoSomething, fake.IsRetryable);
fake.Received(4, x => x.DoSomething());
delay.Received(1, x => x.Received(100));
delay.Received(1, x => x.Received(200));
delay.Received(1, x => x.Received(400));
// Test logging for each retry
AssertInfoLog(logger, 0, 100, 1);
AssertInfoLog(logger, 1, 200, 2);
AssertInfoLog(logger, 2, 400, 3);
}
示例6: SafeMessagingActionAsync
internal static void SafeMessagingActionAsync(Task messageAction, BrokeredMessage message, Action<bool> callback, string actionErrorDescription, string messageId, string subscription, long processingElapsedMilliseconds, long schedulingElapsedMilliseconds, Stopwatch roundtripStopwatch)
{
var retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
retryPolicy.Retrying +=
(s, e) =>
{
Trace.TraceWarning("An error occurred in attempt number {1} to release message {3} in subscription {2}: {0}",
e.LastException.GetType().Name + " - " + e.LastException.Message,
e.CurrentRetryCount,
subscription,
message.MessageId);
};
long messagingActionStart = roundtripStopwatch.ElapsedMilliseconds;
retryPolicy.ExecuteAsync(() => messageAction.ContinueWith(r =>
{
if (r.Exception != null)
{
Exception e = r.Exception;
roundtripStopwatch.Stop();
if (e is MessageLockLostException || e is MessagingException || e is TimeoutException)
{
Trace.TraceWarning(actionErrorDescription, messageId, subscription, e.GetType().Name + " - " + e.Message, processingElapsedMilliseconds, schedulingElapsedMilliseconds, messagingActionStart, roundtripStopwatch.ElapsedMilliseconds);
}
else
{
Trace.TraceError("Unexpected error releasing message in subscription {1}:\r\n{0}", e, subscription);
}
callback(false);
}
else
{
messagingActionStart = roundtripStopwatch.ElapsedMilliseconds;
roundtripStopwatch.Stop();
callback(true);
}
}));
}
示例7: MergesLogInfo
public static async Task MergesLogInfo()
{
var fake = Substitute.For<IFake>();
fake.DoSomething().ReturnsTask(1337, 0);
fake.IsRetryable(1337, null).Returns(true);
fake.IsRetryable(0, null).Returns(false);
var logger = Substitute.For<ILog>();
var delay = Substitute.For<Delay>();
var retryHandler = new RetryPolicy(logger, 100, 10, delay);
await retryHandler.ExecuteAsync(fake.DoSomething, fake.IsRetryable,
(result, loggerInfo) =>
{
loggerInfo["couchbaseDocumentKey"] = "mykey";
loggerInfo["result"] = result;
});
var fields = AssertInfoLog(logger, 0, 100, 1);
Assert.Equal("mykey", fields["couchbaseDocumentKey"]);
Assert.Equal(1337, fields["result"]);
}
示例8: Throws_IfRetriesAreExhausted
public static void Throws_IfRetriesAreExhausted()
{
var fake = Substitute.For<IFake>();
fake.DoSomething().ReturnsTask(1337, 1337);
fake.IsRetryable(1337, null).Returns(true);
fake.IsRetryable(0, null).Returns(false);
var logger = Substitute.For<ILog>();
var delay = Substitute.For<Delay>();
var retryHandler = new RetryPolicy(logger, 100, 2, delay);
var ex = Assert.Throws<RetryFailedException>(() => retryHandler.ExecuteAsync(fake.DoSomething, fake.IsRetryable).GetAwaiter().GetResult());
Assert.Equal("The operation did not succeed after the maximum number of retries (2).", ex.Message);
}
示例9: Throws_WhenCancellationTokenIsSubsequentlyCancelled
public static async void Throws_WhenCancellationTokenIsSubsequentlyCancelled()
{
var logger = Substitute.For<ILog>();
var retryHandler = new RetryPolicy(logger);
var cts = new CancellationTokenSource(500);
var result = retryHandler.ExecuteAsync(async c => { await Task.Delay(4000, c); return true; }, (b, e) => true, cancellationToken: cts.Token);
await Assert.ThrowsAsync<TaskCanceledException>(async () => await result);
Assert.True(result.IsCanceled);
}
示例10: Throws_WhenCancellationTokenIsAlreadyCancelled
public static async void Throws_WhenCancellationTokenIsAlreadyCancelled()
{
var logger = Substitute.For<ILog>();
var retryHandler = new RetryPolicy(logger);
var ex = await Assert.ThrowsAsync<TaskCanceledException>(() => retryHandler.ExecuteAsync(async c => { await Task.Delay(5000, c); return true; }, (b, e) => true, cancellationToken: new CancellationToken(true)));
Assert.True(ex.Task.IsCanceled);
}