三国卡牌客户端基础资源仓库
hch
2 天以前 9b89d57827524ea02d367a717af45e2360319312
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
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Unity Technologies.
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
using System;
using System.Threading;
 
namespace Microsoft.Unity.VisualStudio.Editor
{
    internal class AsyncOperation<T>
    {
        private readonly Func<T> _producer;
        private readonly Func<Exception, T> _exceptionHandler;
        private readonly Action _finalHandler;
        private readonly ManualResetEventSlim _resetEvent;
 
        private T _result;
        private Exception _exception;
 
        private AsyncOperation(Func<T> producer, Func<Exception, T> exceptionHandler, Action finalHandler)
        {
            _producer = producer;
            _exceptionHandler = exceptionHandler;
            _finalHandler = finalHandler;
            _resetEvent = new ManualResetEventSlim(initialState: false);
        }
 
        public static AsyncOperation<T> Run(Func<T> producer, Func<Exception, T> exceptionHandler = null, Action finalHandler = null)
        {
            var task = new AsyncOperation<T>(producer, exceptionHandler, finalHandler);
            task.Run();
            return task;
        }
 
        private void Run()
        {
            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    _result = _producer();
                }
                catch (Exception e)
                {
                    _exception = e;
 
                    if (_exceptionHandler != null)
                    {
                        _result = _exceptionHandler(e);
                    }
                }
                finally
                {
                    _finalHandler?.Invoke();
                    _resetEvent.Set();
                }
            });
        }
 
        private void CheckCompletion()
        {
            if (!_resetEvent.IsSet)
                _resetEvent.Wait();
        }
 
 
        public T Result
        {
            get
            {
                CheckCompletion();
                return _result;
            }
        }
 
        public Exception Exception
        {
            get
            {
                CheckCompletion();
                return _exception;
            }
        }
    }
}