1 /* ****************************************************************************
\r
3 * Copyright (c) Microsoft Corporation. All rights reserved.
\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
9 * You must not remove this notice, or any other, from this software.
\r
11 * ***************************************************************************/
\r
13 namespace System.Web.Mvc.Async {
\r
15 using System.Threading;
\r
17 internal static class SynchronizationContextUtil {
\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
26 public static T Sync<T>(this SynchronizationContext syncContext, Func<T> func) {
\r
27 T theValue = default(T);
\r
28 Exception thrownException = null;
\r
30 syncContext.Send(o => {
\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
41 if (thrownException != null) {
\r
42 throw Error.SynchronizationContextUtil_ExceptionThrown(thrownException);
\r
47 public static void Sync(this SynchronizationContext syncContext, Action action) {
\r
48 Sync<AsyncVoid>(syncContext, () => {
\r
50 return default(AsyncVoid);
\r