summaryrefslogtreecommitdiff
path: root/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Utils/NotifyAwaiter.cs
blob: d84a63c83c7a9ba2863765b19f177088eeb1197d (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
55
56
57
58
59
60
61
62
63
64
using System;
using System.Runtime.CompilerServices;

namespace GodotTools.IdeMessaging.Utils
{
    public class NotifyAwaiter<T> : INotifyCompletion
    {
        private Action continuation;
        private Exception exception;
        private T result;

        public bool IsCompleted { get; private set; }

        public T GetResult()
        {
            if (exception != null)
                throw exception;
            return result;
        }

        public void OnCompleted(Action continuation)
        {
            if (this.continuation != null)
                throw new InvalidOperationException("This awaiter has already been listened");
            this.continuation = continuation;
        }

        public void SetResult(T result)
        {
            if (IsCompleted)
                throw new InvalidOperationException("This awaiter is already completed");

            IsCompleted = true;
            this.result = result;

            continuation?.Invoke();
        }

        public void SetException(Exception exception)
        {
            if (IsCompleted)
                throw new InvalidOperationException("This awaiter is already completed");

            IsCompleted = true;
            this.exception = exception;

            continuation?.Invoke();
        }

        public NotifyAwaiter<T> Reset()
        {
            continuation = null;
            exception = null;
            result = default(T);
            IsCompleted = false;
            return this;
        }

        public NotifyAwaiter<T> GetAwaiter()
        {
            return this;
        }
    }
}