/* **************************************************************************** * * Copyright (c) Microsoft Corporation. All rights reserved. * * This software is subject to the Microsoft Public License (Ms-PL). * A copy of the license can be found in the license.htm file included * in this distribution. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ namespace System.Web.Mvc.Async { using System; using System.Threading; internal static class SynchronizationContextUtil { public static SynchronizationContext GetSynchronizationContext() { // In a runtime environment, SynchronizationContext.Current will be set to an instance // of AspNetSynchronizationContext. In a unit test environment, the Current property // won't be set and we have to create one on the fly. return SynchronizationContext.Current ?? new SynchronizationContext(); } public static T Sync(this SynchronizationContext syncContext, Func func) { T theValue = default(T); Exception thrownException = null; syncContext.Send(o => { try { theValue = func(); } catch (Exception ex) { // by default, the AspNetSynchronizationContext type will swallow thrown exceptions, // so we need to save and propagate them thrownException = ex; } }, null); if (thrownException != null) { throw Error.SynchronizationContextUtil_ExceptionThrown(thrownException); } return theValue; } public static void Sync(this SynchronizationContext syncContext, Action action) { Sync(syncContext, () => { action(); return default(AsyncVoid); }); } } }