Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DynamicEndpointDataSource.cs « TestObjects « UnitTests « test « Routing « Http « src - github.com/dotnet/aspnetcore.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c4d217541360f0e5d62a8fbd75eb926dfcc8f975 (plain)
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
52
53
54
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Threading;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;

namespace Microsoft.AspNetCore.Routing.TestObjects
{
    public class DynamicEndpointDataSource : EndpointDataSource
    {
        private readonly List<Endpoint> _endpoints;
        private CancellationTokenSource _cts;
        private CancellationChangeToken _changeToken;
        private readonly object _lock;

        public DynamicEndpointDataSource(params Endpoint[] endpoints)
        {
            _endpoints = new List<Endpoint>();
            _endpoints.AddRange(endpoints);
            _lock = new object();

            CreateChangeToken();
        }

        public override IChangeToken GetChangeToken() => _changeToken;

        public override IReadOnlyList<Endpoint> Endpoints => _endpoints;

        // Trigger change
        public void AddEndpoint(Endpoint endpoint)
        {
            _endpoints.Add(endpoint);

            // Capture the old tokens so that we can raise the callbacks on them. This is important so that
            // consumers do not register callbacks on an inflight event causing a stackoverflow.
            var oldTokenSource = _cts;
            var oldToken = _changeToken;

            CreateChangeToken();

            // Raise consumer callbacks. Any new callback registration would happen on the new token
            // created in earlier step.
            oldTokenSource.Cancel();
        }

        private void CreateChangeToken()
        {
            _cts = new CancellationTokenSource();
            _changeToken = new CancellationChangeToken(_cts.Token);
        }
    }
}