1 //
2 // Copyright (c) 2010-2022 Antmicro
3 // Copyright (c) 2011-2015 Realtime Embedded
4 //
5 // This file is licensed under the MIT License.
6 // Full license text is available in 'licenses/MIT.txt'.
7 //
8 using System;
9 using System.Threading;
10 
11 namespace Antmicro.Renode.Testing
12 {
13     public static class TimeoutExecutor
14     {
Execute(Func<T> func, int timeout)15         public static T Execute<T>(Func<T> func, int timeout)
16         {
17             T result;
18             TryExecute(func, timeout, out result);
19             return result;
20         }
21 
TryExecute(Func<T> func, int timeout, out T result)22         public static bool TryExecute<T>(Func<T> func, int timeout, out T result)
23         {
24             T res = default(T);
25             var thread = new Thread(() => res = func())
26             {
27                 IsBackground = true,
28                 Name = typeof(TimeoutExecutor).Name
29             };
30             thread.Start();
31             var finished = thread.Join(timeout);
32             if (!finished)
33             {
34             #if NET
35                 thread.Interrupt();
36             #else
37                 thread.Abort();
38             #endif
39             }
40             result = res;
41             return finished;
42         }
43 
WaitForEvent(ManualResetEvent e, int timeout)44         public static bool WaitForEvent(ManualResetEvent e, int timeout)
45         {
46             return e.WaitOne(timeout);
47         }
48     }
49 }
50 
51