Last active
October 22, 2015 21:13
-
-
Save nzbart/16a608fb45c9ed707e04 to your computer and use it in GitHub Desktop.
Create an instance of the AspNetSynchronizationContext, which is internal and is not easily constructed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static SynchronizationContext CreateAspNetSynchronizationContext() | |
{ | |
const string taskFriendlyConfigName = "aspnet:UseTaskFriendlySynchronizationContext"; | |
var originalConfigSetting = ConfigurationManager.AppSettings[taskFriendlyConfigName]; | |
ConfigurationManager.AppSettings[taskFriendlyConfigName] = "true"; | |
try | |
{ | |
TextWriter writer = new StringWriter(); | |
HttpRequest rx = new HttpRequest("", "http://example.com", ""); | |
HttpResponse tx = new HttpResponse(writer); | |
HttpContext ctx = new HttpContext(rx, tx); | |
ctx.AllowAsyncDuringSyncStages = true; | |
return (SynchronizationContext)ctx.GetType().GetProperty("SyncContext", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true).Invoke(ctx, null); | |
} | |
finally | |
{ | |
ConfigurationManager.AppSettings[taskFriendlyConfigName] = originalConfigSetting; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment