diff options
| author | Roy Ben Shabat <Roy.mail.net@gmail.com> | 2020-08-25 03:41:56 +0300 |
|---|---|---|
| committer | Roy Ben Shabat <Roy.mail.net@gmail.com> | 2020-08-25 03:41:56 +0300 |
| commit | 16389f246971059da6e4476808d35dc1022f8870 (patch) | |
| tree | 6b881d78ebd7f79561ecdfc3635aa702f5848b5a /Software/Visual_Studio/Tango.Core/Threading | |
| parent | 07173155f536396f80501839b336adac76c90f7b (diff) | |
| download | Tango-16389f246971059da6e4476808d35dc1022f8870.tar.gz Tango-16389f246971059da6e4476808d35dc1022f8870.zip | |
Improved PPC application start event logging.
Improved PP application shutdown finalization + Added termination event.
Diffstat (limited to 'Software/Visual_Studio/Tango.Core/Threading')
| -rw-r--r-- | Software/Visual_Studio/Tango.Core/Threading/LimitedTimeTask.cs | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/Software/Visual_Studio/Tango.Core/Threading/LimitedTimeTask.cs b/Software/Visual_Studio/Tango.Core/Threading/LimitedTimeTask.cs new file mode 100644 index 000000000..6be8f80d9 --- /dev/null +++ b/Software/Visual_Studio/Tango.Core/Threading/LimitedTimeTask.cs @@ -0,0 +1,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(); + } + } +} |
