HttpClient.SendAsync()。ContinueWith()任务在完成之前死亡

时间:2018-07-24 15:30:19

标签: c# asynchronous task race-condition

我正在编写一个ASP.NET MVC应用程序,并且有一个方法可以调出Web服务。

protected Task ExecuteRequest(HttpClient client, HttpRequestMessage restRequest)
{
    SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
    scheduler = TaskScheduler.FromCurrentSynchronizationContext();

    Task requestTask = client.SendAsync(restRequest).ContinueWith(antecendent =>
            {
                # Process response. Break point here. Doesn't seem to be running unless I spend time stepping through code in debug mode.
            }, scheduler);
    return requestTask;
}


/* ======================================================================
 * This stuff probably doesn't matter but just in case, I'm including it.
 * ====================================================================== */
protected HttpClient GetClient() {
    var clientHandler = new HttpClientHandler();
    if (clientHandler.SupportsAutomaticDecompression)
    {
        clientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    }
    HttpClient client = new HttpClient(clientHandler);
    return client;
}

然后,当我调用ExecuteRequest时:Task request = ExecuteRequest(GetClient(), myRequestMessage); ContinueWith中的断点不会触发。相反, 触发此调用的MVC请求完成,并且页面完成加载,并且ContinueWith的前一个条件中从未调用任何代码。我已经放入loggs来查看代码是否被命中,但是我没有放入其中,因为没有日志写入其文件,并且该代码中逻辑的结果似乎都没有发生。 / p>

我的假设是,当MVC响应完成时,由MVC请求调用的任务与主线程一起死亡。如果我在任务启动后以调试方式逐步执行代码,有时代码会运行并且会遇到断点,因此看起来像是竞争条件。

我看过This post,但他们不得不采取的解决方案是等待任务完成。我不想等待服务调用完成,然后再将响应返回给用户。如果任务尚未完成,我将稍后让用户刷新以查看结果,该结果仍应在单独的线程中在后台运行...但是问题是结果永远不会发生。

为什么似乎没有运行“#Process response”位?

0 个答案:

没有答案