public static AsyncSynchronizationContext Register() { var syncContext = Current; AsyncSynchronizationContext customSynchronizationContext = null; if (syncContext != null) { customSynchronizationContext = syncContext as AsyncSynchronizationContext; if (customSynchronizationContext == null) { customSynchronizationContext = new AsyncSynchronizationContext(syncContext); try { SetSynchronizationContext(customSynchronizationContext); } catch (Exception ex) { Console.WriteLine("SetSynchronizationContext Exception: {0}", ex); } } } return customSynchronizationContext; }
/// <summary> /// Registers the async handler for unawaited void and Task unhandled exceptions that are thrown in the application. /// </summary> /// <remarks> /// This function might be needed in special cases where the synchronization context could be <c>null</c> in early initialization. /// The async handlers are registered in the initialization process of the component. /// </remarks> public void RegisterAsyncHandlerContext() { AsyncSynchronizationContext.ExceptionCaught += SyncContextExceptionHandler; AsyncSynchronizationContext.Register(); }