Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 继续使用方法isn';t等待异步任务完成_C#_Asynchronous_Task_Asp.net Web Api - Fatal编程技术网

C# 继续使用方法isn';t等待异步任务完成

C# 继续使用方法isn';t等待异步任务完成,c#,asynchronous,task,asp.net-web-api,C#,Asynchronous,Task,Asp.net Web Api,我正在尝试记录对API的请求和响应。我目前正在使用一个delegatingHandler,它捕获httpwebresponses和httpwebrequests 处理程序: protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { LogRequest(request)

我正在尝试记录对API的请求和响应。我目前正在使用一个delegatingHandler,它捕获httpwebresponses和httpwebrequests

处理程序:

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        LogRequest(request);
        return base.SendAsync(request, cancellationToken).ContinueWith((task) =>
             {
                 HttpResponseMessage response = task.Result;
                 LogResponse(response);
                 return response;
             });
    }
当我尝试将内容插入存储库中的数据库时,我得到一个空异常。但是当我逐步进入内容对象时,它会被响应填充。我想我正在尝试在请求完成之前将数据插入数据库

我不想等待它,因为这违背了使用异步请求的目的,如何在请求完成时连接它以运行logresponse方法?我认为continueWith会处理这个问题,并在任务完成时运行操作(这是否意味着请求的下载不一定完成?)


有什么想法吗?

您正在将
info.Content
异步设置为调用
\u repository.LogResponse(info)
LogResponse
很可能在继续执行之前被调用。将调用移动到continuation正文中的
LogResponse
。例如:

if (response.Content != null)
{
    response.Content.ReadAsStringAsync().ContinueWith((task) =>
            { 
                info.Content = task.Result;
                _repository.LogResponse(info);
            }
        );
}

您可以尝试以下示例:

private void LogResponse(HttpResponseMessage response)
{
    ApiResponse info = new ApiResponse();
    //Populate response obj   

    if (response.Content != null)
    {
        var info = await response.Content.ReadAsStringAsync();
        _repository.LogResponse(info);
    }
}

尝试调试打印以查看代码流。True。您要么等待任务完成,要么在任务结束时登录到任务内部的存储库。关键是,在登录之前必须彻底运行代码。op是否使用VS 11值得怀疑这在VS 2010中是可用的。很多人都不能使用异步编程的新版本“不受支持并使用您自己承担风险的技术预览”,像这样的错误正困扰着我!
if (response.Content != null)
{
    var task = response.Content.ReadAsStringAsync().ContinueWith((task) =>
                       { 
                           info.Content = task.Result;
                       });

    task.Wait();
}

_repository.LogResponse(info);
private void LogResponse(HttpResponseMessage response)
{
    ApiResponse info = new ApiResponse();
    //Populate response obj   

    if (response.Content != null)
    {
        var info = await response.Content.ReadAsStringAsync();
        _repository.LogResponse(info);
    }
}