In order to force scheduling of the continuation on the request context thread, you need to specify the TaskScheduler
that should be used when scheduling the continuation.
public async Task<ActionResult> Index()
{
Log("before GetAsync");
await new HttpClient().GetAsync("http://www.example.com/")
.ContinueWith(request =>
{
Log("ContinueWith");
request.Result.EnsureSuccessStatusCode();
},
TaskContinuationOptions.AttachedToParent,
CancellationToken.None,
TaskScheduler.FromCurrentSynchronizationContext());
return View();
}
Howver, you are using await
which automatically marshals continuations on to the current SynchronizationContext
. You should be able to do this:
public async Task<ActionResult> Index()
{
Log("before GetAsync");
HttpResponseMessage request = await new HttpClient().GetAsync("http://www.example.com/");
//everything below here is you 'continuation' on the request context
Log("ContinueWith");
request.EnsureSuccessStatusCode();
return View();
}