aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Core/Threading/LimitedTimeTask.cs
blob: 6be8f80d93d81e9caae2de310a6f7b2ec12e6b27 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tango.Core.Threading
{
    /// <summary>
    /// Represents a task that will be awaited for a limited time.
    /// If the timeout has reached, the task will return and will continue in the background.
    /// </summary>
    public class LimitedTimeTask
    {
        private Action _action;
        private TimeSpan _timeout;
        private bool _completed;

        public LimitedTimeTask(Action action, TimeSpan timeout)
        {
            _action = action;
            _timeout = timeout;
        }

        public Task Run()
        {
            TaskCompletionSource<Object> completion = new TaskCompletionSource<object>();

            ThreadFactory.StartNew(() =>
            {
                try
                {
                    _action?.Invoke();

                    if (!_completed)
                    {
                        _completed = true;

                        try
                        {
                            completion.SetResult(true);
                        }
                        catch { }
                    }
                }
                catch (Exception ex)
                {
                    if (!_completed)
                    {
                        _completed = true;
                        try
                        {
                            completion.SetException(ex);
                        }
                        catch { }
                    }
                }
            });

            TimeoutTask.StartNew(() =>
            {
                if (!_completed)
                {
                    _completed = true;
                    try
                    {
                        completion.SetException(new TimeoutException($"The limited time task did not complete within the given time of {(int)_timeout.TotalMilliseconds} milliseconds and will continue in the background if possible."));
                    }
                    catch { }
                }
            }, _timeout);

            return completion.Task;
        }

        public static Task StartNew(Action action, TimeSpan timeout)
        {
            return new LimitedTimeTask(action, timeout).Run();
        }
    }
}