~ruther/NosSmooth.Local

ref: ce0260d5b61a99ecbbd13177283632c4a7a2e28c NosSmooth.Local/src/Core/NosSmooth.LocalBinding/NosThreadSynchronizer.cs -rw-r--r-- 6.0 KiB
ce0260d5 — František Boháček feat: update to managed and raw client 2 years ago
                                                                                
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//
//  NosThreadSynchronizer.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NosSmooth.LocalBinding.Hooks;
using NosSmooth.LocalBinding.Options;
using Remora.Results;

namespace NosSmooth.LocalBinding;

/// <summary>
/// Synchronizes with NosTale thread using a periodic function.
/// </summary>
public class NosThreadSynchronizer
{
    private readonly IPeriodicHook _periodicHook;
    private readonly ILogger<NosThreadSynchronizer> _logger;
    private readonly NosThreadSynchronizerOptions _options;
    private readonly ConcurrentQueue<SyncOperation> _queuedOperations;
    private Thread? _nostaleThread;

    /// <summary>
    /// Initializes a new instance of the <see cref="NosThreadSynchronizer"/> class.
    /// </summary>
    /// <param name="periodicHook">The periodic hook.</param>
    /// <param name="logger">The logger.</param>
    /// <param name="options">The options.</param>
    public NosThreadSynchronizer
    (
        IPeriodicHook periodicHook,
        ILogger<NosThreadSynchronizer> logger,
        IOptions<NosThreadSynchronizerOptions> options
    )
    {
        _periodicHook = periodicHook;
        _logger = logger;
        _options = options.Value;
        _queuedOperations = new ConcurrentQueue<SyncOperation>();
    }

    /// <summary>
    /// Gets whether the current thread is a NosTale thread.
    /// </summary>
    public bool IsSynchronized => _nostaleThread == Thread.CurrentThread;

    /// <summary>
    /// Start the synchronizer operation.
    /// </summary>
    public void StartSynchronizer()
    {
        _periodicHook.Called += PeriodicCall;
    }

    /// <summary>
    /// Stop the synchronizer operation.
    /// </summary>
    public void StopSynchronizer()
    {
        _periodicHook.Called -= PeriodicCall;
    }

    private void PeriodicCall(object? owner, System.EventArgs eventArgs)
    {
        _nostaleThread = Thread.CurrentThread;
        var tasks = _options.MaxTasksPerIteration;

        while (tasks-- > 0 && _queuedOperations.TryDequeue(out var operation))
        {
            ExecuteOperation(operation);
        }
    }

    private void ExecuteOperation(SyncOperation operation)
    {
        try
        {
            var result = operation.Action();
            operation.Result = result;
        }
        catch (Exception e)
        {
            _logger.LogError(e, "Synchronizer obtained an exception");
            operation.Result = (Result)e;
        }

        if (operation.CancellationTokenSource is not null)
        {
            try
            {
                operation.CancellationTokenSource.Cancel();
            }
            catch (Exception)
            {
                // ignore
            }
        }
    }

    /// <summary>
    /// Enqueue the given operation to execute on next frame.
    /// </summary>
    /// <param name="action">The action to execute.</param>
    /// <param name="executeIfSynchronized">Whether to execute the operation instantly in case we are on the NosTale thread.</param>
    public void EnqueueOperation(Action action, bool executeIfSynchronized = true)
    {
        if (executeIfSynchronized && IsSynchronized)
        { // we are synchronized, no need to wait.
            action();
            return;
        }

        _queuedOperations.Enqueue
        (
            new SyncOperation
            (
                () =>
                {
                    action();
                    return Result.FromSuccess();
                },
                null
            )
        );
    }

    /// <summary>
    /// Synchronizes to NosTale thread, executes the given action and returns its result.
    /// </summary>
    /// <param name="action">The action to execute.</param>
    /// <param name="ct">The cancellation token used for cancelling the operation.</param>
    /// <returns>The result of the action.</returns>
    public async Task<Result> SynchronizeAsync(Func<Result> action, CancellationToken ct = default)
    {
        return (Result)await CommonSynchronizeAsync(() => action(), ct);
    }

    /// <summary>
    /// Synchronizes to NosTale thread, executes the given action and returns its result.
    /// </summary>
    /// <param name="action">The action to execute.</param>
    /// <param name="ct">The cancellation token used for cancelling the operation.</param>
    /// <returns>The result of the action.</returns>
    /// <typeparam name="T">The type of the result.</typeparam>
    public async Task<Result<T>> SynchronizeAsync<T>(Func<Result<T>> action, CancellationToken ct = default)
    {
        return (Result<T>)await CommonSynchronizeAsync(() => action(), ct);
    }

    private async Task<IResult> CommonSynchronizeAsync(Func<IResult> action, CancellationToken ct = default)
    {
        if (IsSynchronized)
        { // we are already synchronized, execute the action.
            try
            {
                return action();
            }
            catch (Exception e)
            {
                return (Result)e;
            }
        }

        var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(ct);
        var syncOperation = new SyncOperation(action, linkedSource);
        _queuedOperations.Enqueue(syncOperation);

        try
        {
            await Task.Delay(Timeout.Infinite, linkedSource.Token);
        }
        catch (OperationCanceledException)
        {
            if (ct.IsCancellationRequested)
            { // Throw in case the top token was cancelled.
                throw;
            }
        }
        catch (Exception e)
        {
            return (Result)new ExceptionError(e);
        }

        return syncOperation.Result ?? Result.FromSuccess();
    }

    private record SyncOperation(Func<IResult> Action, CancellationTokenSource? CancellationTokenSource)
    {
        public IResult? Result { get; set; }
    }
}
Do not follow this link