forked from florentbr/SeleniumBasic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadExt.cs
More file actions
38 lines (33 loc) · 1.16 KB
/
ThreadExt.cs
File metadata and controls
38 lines (33 loc) · 1.16 KB
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
using System;
using System.Threading;
namespace Selenium.Internal {
class ThreadExt {
/// <summary>
/// Invoke a function on a new single thread.
/// </summary>
/// <typeparam name="T">Returned value</typeparam>
/// <param name="func">Function</param>
/// <param name="timeout">Execution timeout</param>
/// <returns></returns>
public static T RunSTA<T>(Func<T> func, int timeout) {
T result = default(T);
Exception exception = null;
using (var evt = new EventWaitHandle(false, EventResetMode.ManualReset)) {
Thread thread = new Thread(() => {
try {
result = func();
} catch (Exception ex) {
exception = ex;
}
evt.Set();
});
thread.TrySetApartmentState(ApartmentState.STA);
thread.Start();
evt.WaitOne(timeout, true);
}
if (exception != null)
throw new SeleniumException(exception);
return result;
}
}
}