【问题标题】:Missunderstanding with task, async, await, example with SendRequestAsync对任务、异步、等待、SendRequestAsync 示例的误解
【发布时间】:2014-05-22 20:00:07
【问题描述】:

如果我调用这个方法 (1.) 什么都不会发生,我也不知道为什么。 如果我只是调用 model.TestConnection(null);没有结果我打断点 1 但我不等待结果。

那么,为什么我在调用 model.TestConnection(null).Result 时没有命中任何断点? 为什么我只调用 model.TestConnection(null); 时会碰到它们?

GetUrl 方法调用 SendRequestAsync 并等待其结果,然后返回其内容。 这一切都是作为一项任务发生的,因此您可以等待 GetUrl 来获取内容。但我这边似乎对任务并行库 (TPL) 存在很大的误解。

  1. var result = model.TestConnection(null).Result;
    
  2. public class CcuMockModel : CcuModelBase, ICcuModel
    {
        public Task<CheckLoginResult> TestConnection(string url)
        {
           return GetUrl(@"http://localhost:8080/api/getObjects");
        }
    }
    
  3. public class CcuModelBase
    {
        public async Task<CheckLoginResult> GetUrl(string url)
        {
            var aHBPF = new HttpBaseProtocolFilter();
            aHBPF.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
            aHBPF.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
    
            var client = new HttpClient(aHBPF);
    
            var request = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
    
            HttpResponseMessage response;
            try
            {
                response = await client.SendRequestAsync(request);
                // Breakpoint 1
                return new CheckLoginResult()
                {
                    Content = response.Content.ToString(),
                    Status = CheckLoginResult.ErrorCode.Ok
                };
            }
            catch (Exception ex)
            {
            }
            // Breakpoint 2
            return new CheckLoginResult() {Status = CheckLoginResult.ErrorCode.Failed};
        }
    }
    

【问题讨论】:

  • 感谢反对票。
  • 您可能因为格式不正确的问题而被否决。究竟是什么问题?
  • 我编辑了我的问题,感谢反馈。
  • 您似乎遇到了死锁。 client.SendRequestAsync 之后的继续无法运行,因为如果当前同步上下文想要在同一线程上运行继续,则调用者会阻塞返回的任务 model.TestConnection(null).Result。见blog.stephencleary.com/2012/07/dont-block-on-async-code.html

标签: c# asynchronous task-parallel-library task async-await


【解决方案1】:

感谢李提供链接http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html 这解释了很多,并帮助我理解了任务、异步和等待。

我阻止了我的任务

var result = model.TestConnection(null).Result;

现在我在等待,一切正常。

private async static void Testing()
{
    var result = await model.TestConnection(null);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 2014-09-06
    • 2013-02-10
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    相关资源
    最近更新 更多