New tests.
[mono.git] / mcs / class / System.Web.Mvc2 / System.Web.Mvc / Async / SynchronizationContextUtil.cs
1 /* ****************************************************************************\r
2  *\r
3  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4  *\r
5  * This software is subject to the Microsoft Public License (Ms-PL). \r
6  * A copy of the license can be found in the license.htm file included \r
7  * in this distribution.\r
8  *\r
9  * You must not remove this notice, or any other, from this software.\r
10  *\r
11  * ***************************************************************************/\r
12 \r
13 namespace System.Web.Mvc.Async {\r
14     using System;\r
15     using System.Threading;\r
16 \r
17     internal static class SynchronizationContextUtil {\r
18 \r
19         public static SynchronizationContext GetSynchronizationContext() {\r
20             // In a runtime environment, SynchronizationContext.Current will be set to an instance\r
21             // of AspNetSynchronizationContext. In a unit test environment, the Current property\r
22             // won't be set and we have to create one on the fly.\r
23             return SynchronizationContext.Current ?? new SynchronizationContext();\r
24         }\r
25 \r
26         public static T Sync<T>(this SynchronizationContext syncContext, Func<T> func) {\r
27             T theValue = default(T);\r
28             Exception thrownException = null;\r
29 \r
30             syncContext.Send(o => {\r
31                 try {\r
32                     theValue = func();\r
33                 }\r
34                 catch (Exception ex) {\r
35                     // by default, the AspNetSynchronizationContext type will swallow thrown exceptions,\r
36                     // so we need to save and propagate them\r
37                     thrownException = ex;\r
38                 }\r
39             }, null);\r
40 \r
41             if (thrownException != null) {\r
42                 throw Error.SynchronizationContextUtil_ExceptionThrown(thrownException);\r
43             }\r
44             return theValue;\r
45         }\r
46 \r
47         public static void Sync(this SynchronizationContext syncContext, Action action) {\r
48             Sync<AsyncVoid>(syncContext, () => {\r
49                 action();\r
50                 return default(AsyncVoid);\r
51             });\r
52         }\r
53 \r
54     }\r
55 }\r