Skip to content

Commit d84c21c

Browse files
committed
use AsyncLocal for Cancellable token
1 parent e08be38 commit d84c21c

File tree

1 file changed

+8
-25
lines changed

1 file changed

+8
-25
lines changed

src/Compiler/Utilities/Cancellable.fs

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,37 +6,20 @@ open Internal.Utilities.Library
66

77
[<Sealed>]
88
type Cancellable =
9-
[<ThreadStatic; DefaultValue>]
10-
static val mutable private tokens: CancellationToken list
9+
static let token = AsyncLocal<CancellationToken>()
10+
11+
static member UsingToken(ct) =
12+
let previousToken = token.Value
13+
token.Value <- ct
1114

12-
static let disposable =
1315
{ new IDisposable with
14-
member this.Dispose() =
15-
Cancellable.Tokens <- Cancellable.Tokens |> List.tail
16+
member this.Dispose() = token.Value <- previousToken
1617
}
1718

18-
static member Tokens
19-
with private get () =
20-
match box Cancellable.tokens with
21-
| Null -> []
22-
| _ -> Cancellable.tokens
23-
and private set v = Cancellable.tokens <- v
24-
25-
static member UsingToken(ct) =
26-
Cancellable.Tokens <- ct :: Cancellable.Tokens
27-
disposable
28-
29-
static member Token =
30-
match Cancellable.Tokens with
31-
| [] -> CancellationToken.None
32-
| token :: _ -> token
19+
static member Token = token.Value
3320

34-
/// There may be multiple tokens if `UsingToken` is called multiple times, producing scoped structure.
35-
/// We're interested in the current, i.e. the most recent, one.
3621
static member CheckAndThrow() =
37-
match Cancellable.Tokens with
38-
| [] -> ()
39-
| token :: _ -> token.ThrowIfCancellationRequested()
22+
token.Value.ThrowIfCancellationRequested()
4023

4124
namespace Internal.Utilities.Library
4225

0 commit comments

Comments
 (0)