~ruther/NosSmooth

ref: 213fe53ae3a31d69b20543002b447347cf7893c0 NosSmooth/Core/NosSmooth.Core/Commands/Control/TakeControlCommandHandler.cs -rw-r--r-- 1.8 KiB
213fe53a — Rutherther Merge pull request #81 from Rutherther/feat/pathfinding-mates 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
//
//  TakeControlCommandHandler.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;
using System.Threading;
using System.Threading.Tasks;
using Remora.Results;

namespace NosSmooth.Core.Commands.Control;

/// <summary>
/// Handles <see cref="TakeControlCommand"/>.
/// </summary>
internal class TakeControlCommandHandler : ICommandHandler<TakeControlCommand>
{
    private readonly ControlCommands _commands;

    /// <summary>
    /// Initializes a new instance of the <see cref="TakeControlCommandHandler"/> class.
    /// </summary>
    /// <param name="commands">The control commands.</param>
    public TakeControlCommandHandler(ControlCommands commands)
    {
        _commands = commands;
    }

    /// <inheritdoc />
    public async Task<Result> HandleCommand(TakeControlCommand command, CancellationToken ct = default)
    {
        using var source = CancellationTokenSource.CreateLinkedTokenSource(ct);
        var registrationResult = await _commands.RegisterAsync(command, source, ct);
        if (!registrationResult.IsSuccess)
        {
            return registrationResult;
        }

        var token = source.Token;
        try
        {
            var handlerResult = await command.HandleCallback(token);
            await _commands.FinishAsync(command.Group);

            return handlerResult;
        }
        catch (Exception e)
        {
            return e;
        }
        finally
        {
            if (!source.IsCancellationRequested)
            {
                try
                {
                    source.Cancel();
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
    }
}
Do not follow this link