forked from madelson/DistributedLock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeoutTask.cs
More file actions
41 lines (37 loc) · 1.38 KB
/
TimeoutTask.cs
File metadata and controls
41 lines (37 loc) · 1.38 KB
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
using Medallion.Threading.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Medallion.Threading.Redis
{
/// <summary>
/// Acts as a <see cref="Task.Delay(TimeSpan, CancellationToken)"/> which is cleaned up when
/// the <see cref="TimeoutTask"/> gets disposed
/// </summary>
internal readonly struct TimeoutTask : IDisposable
{
private readonly CancellationTokenSource _cleanupTokenSource;
private readonly CancellationTokenSource? _linkedTokenSource;
public TimeoutTask(TimeoutValue timeout, CancellationToken cancellationToken)
{
this._cleanupTokenSource = new CancellationTokenSource();
this._linkedTokenSource = cancellationToken.CanBeCanceled
? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, this._cleanupTokenSource.Token)
: null;
this.Task = Task.Delay(timeout.TimeSpan, this._linkedTokenSource?.Token ?? this._cleanupTokenSource.Token);
}
public Task Task { get; }
public void Dispose()
{
try { this._cleanupTokenSource.Cancel(); }
finally
{
this._linkedTokenSource?.Dispose();
this._cleanupTokenSource.Dispose();
}
}
}
}