Class Awaiter
Provides a set of static methods for awaiting asynchronous operations.
public static class Awaiter
- Inheritance
-
Awaiter
Examples
The following example retries an asynchronous operation until it succeeds or a timeout is reached. The delegate returns UnsuccessfulValue twice before returning SuccessfulValue, and the output confirms the operation succeeded after three attempts.
using System;
using System.Threading.Tasks;
using Cuemon.Threading;
namespace Cuemon.Threading;
public class AwaiterExample
{
public async Task DemonstrateAsync()
{
var attempt = 0;
var result = await Awaiter.RunUntilSuccessfulOrTimeoutAsync(() =>
{
attempt++;
if (attempt < 3)
{
return Task.FromResult<ConditionalValue>(new UnsuccessfulValue());
}
return Task.FromResult<ConditionalValue>(new SuccessfulValue());
}, options =>
{
options.Timeout = TimeSpan.FromSeconds(5);
options.Delay = TimeSpan.FromMilliseconds(100);
});
Console.WriteLine($"Succeeded after {attempt} attempts: {result.Succeeded}");
}
}
Methods
RunUntilSuccessfulOrTimeoutAsync(Func<Task<ConditionalValue>>, Action<AsyncRunOptions>)
Repeatedly invokes the specified asynchronous method until it succeeds or the configured Timeout is reached.
public static Task<ConditionalValue> RunUntilSuccessfulOrTimeoutAsync(Func<Task<ConditionalValue>> method, Action<AsyncRunOptions> setup = null)
Parameters
methodFunc<Task<ConditionalValue>>The asynchronous function delegate to execute, returning a ConditionalValue indicating success or failure.
setupAction<AsyncRunOptions>The AsyncRunOptions which may be configured.
Returns
- Task<ConditionalValue>
A task that represents the asynchronous operation. The task result contains the ConditionalValue returned by the last invocation of
method, or an unsuccessful value if the timeout is reached.
Remarks
The method is invoked repeatedly with a delay specified by Delay until it returns a successful ConditionalValue or the timeout specified by Timeout is reached.
Potential exceptions thrown by method are caught and collected. If the operation does not succeed before the timeout, UnsuccessfulValue will be conditionally initialized:
1: No caught exceptions; initialized with default constructor,
2: One caught exception; initialized with caught exception,
3: Two or more exceptions; initialized with AggregateException containing all exceptions.