Safe Execution in .NET: HSafe, Retries and Timeboxing
Turn exceptions into results, retry with backoff, and put a deadline on slow work with HSafe and TryOrFailWithGrace.
Applies to H.Necessaire 4.0.5.
Third-party code throws, networks flake and disks fill up. H.Necessaire gives you three levels of defence, from a quick try/catch replacement to timeboxed execution. All of them are in the core package, and most return an OperationResult so failure is a value you can inspect rather than an exception you must catch.
Install
dotnet add package H.NecessaireHSafe.Run: turn exceptions into results
OperationResult<int> parsed = HSafe.Run(() => int.Parse(text), tag: "parse the quantity");
if (!parsed.IsSuccessful)
log.Warn(parsed.Reason); // "Error occured while trying to parse the quantity. Reason: ..."
OperationResult upload = await HSafe.Run(async () => await client.UploadAsync(file), tag: "upload the file");HSafe.Run has overloads for Action, Func<T>, Func<Task> and Func<Task<T>>, plus variants that take up to six arguments so you can pass a method group without a lambda. The optional tag names the action in the failure message. The exception, including inner exceptions, ends up in the result's reason and comments.
TryOrFailWithGrace: retries with backoff
When you need a few attempts rather than a result, use the extension on Action or Func<Task>:
await new Func<Task>(async () => await client.PingAsync())
.TryOrFailWithGrace(
numberOfTimes: 4,
onRetry: ex => Console.WriteLine($"Retrying: {ex.Message}"),
onFail: ex => Console.WriteLine($"Gave up: {ex.Message}"),
millisecondsToSleepBetweenRetries: 500);Behaviour to keep in mind:
numberOfTimesis the total number of attempts, and its default is1, which means no retry at all unless you raise it.- The sleep between attempts starts at
millisecondsToSleepBetweenRetriesand grows by a factor of 1.3 each time, capped at 10 seconds per sleep. - The sleep uses
Thread.Sleep, even in the async overloads, so it blocks the calling thread. - Exceptions thrown inside
onRetryandonFailare swallowed. - After the last attempt fails,
onFailruns and the method returns normally: nothing is rethrown.
HSafe.RunWithRetry: retry until a condition holds
string token = await HSafe.RunWithRetry(
async () => await authClient.GetTokenAsync(),
successCondition: t => !string.IsNullOrEmpty(t),
maxRetries: 3,
timeoutScaleInMs: .27);The action is retried while it throws or while successCondition returns false. The wait between attempts grows linearly. Two things the signature doesn't tell you:
- Despite its name,
timeoutScaleInMsis used as seconds (TimeSpan.FromSeconds), so the default.27means roughly a quarter of a second, scaled up per retry. maxRetries: 3means up to four attempts in total, and when they are exhausted the method simply returns the last value (or nothing) with no failure signal. Check the returned value, or preferTryOrFailWithGracewith anonFailhandler if you need to know it gave up.
HSafe.RunTimeboxed: give it a deadline
OperationResult<TimeSpan?> run = await HSafe.RunTimeboxed(
TimeSpan.FromSeconds(5),
async cancellationToken => await sync.RunAsync(cancellationToken));
if (!run.IsSuccessful)
log.Warn(run.Reason); // e.g. "Execution timed out after 00:00:05"
else
log.Info($"Took {run.Payload}"); // measured execution timeThe action receives a CancellationToken that is cancelled when the time is up. The timebox races the action against the deadline, so for the work to actually stop early your code must observe the token.
Reading values defensively
string city = customer.SafeRead(c => c.Address.City, fallbakValue: "Unknown");
OperationResult<string> detailed = customer.TryRead(c => c.Address.City);SafeRead returns the value or the fallback if the selector throws (for example on a null reference). TryRead returns the same information as an OperationResult. Note the parameter's spelling in the source: fallbakValue.
Choosing
| Need | Use |
|---|---|
| Run something risky once and get a result | HSafe.Run |
| A few attempts with backoff, then give up quietly | TryOrFailWithGrace |
| Retry until a value looks right | HSafe.RunWithRetry |
| A hard time limit | HSafe.RunTimeboxed |
| Read a possibly-null chain without a try/catch | SafeRead / TryRead |