-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathTryFinallyEffect.cs
51 lines (44 loc) · 1.43 KB
/
TryFinallyEffect.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Copyright (c) TotalSoft.
// This source code is licensed under the MIT license.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NBB.Core.Effects
{
public class TryFinally
{
public class SideEffect<T> : ISideEffect<T>, IAmHandledBy<Handler<T>>
{
public Effect<T> InnerEffect { get; }
public Action Compensation { get; }
public SideEffect(Effect<T> innerEffect, Action compensation)
{
InnerEffect = innerEffect;
Compensation = compensation;
}
}
public class Handler<T> : ISideEffectHandler<SideEffect<T>, T>
{
private readonly IInterpreter _interpreter;
public Handler(IInterpreter interpreter)
{
_interpreter = interpreter;
}
public async Task<T> Handle(SideEffect<T> sideEffect, CancellationToken cancellationToken = default)
{
try
{
return await _interpreter.Interpret(sideEffect.InnerEffect, cancellationToken);
}
finally
{
sideEffect.Compensation.Invoke();
}
}
}
public static SideEffect<T> From<T>(Effect<T> innerEffect, Action compensation)
{
return new(innerEffect, compensation);
}
}
}