Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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
Json 使用HttpContent.ReadAsStringAsync等待vs.结果_Json_Asynchronous_Asp.net Web Api_Async Await_Httpcontent - Fatal编程技术网

Json 使用HttpContent.ReadAsStringAsync等待vs.结果

Json 使用HttpContent.ReadAsStringAsync等待vs.结果,json,asynchronous,asp.net-web-api,async-await,httpcontent,Json,Asynchronous,Asp.net Web Api,Async Await,Httpcontent,我有一个自定义模型活页夹: public class JsonPolyModelBinder : IModelBinder { private readonly JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; public bool BindModel(HttpActionContext actionContext

我有一个自定义模型活页夹:

public class JsonPolyModelBinder : IModelBinder
{
    private readonly JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto };

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var content = actionContext.Request.Content;
        var json = content.ReadAsStringAsync().Result;
        var obj = JsonConvert.DeserializeObject(json, bindingContext.ModelType, settings);
        bindingContext.Model = obj;
        return true;
    }
}
对于较大的负载,content.ReadAsStringAsync().Result似乎使我的web请求超时

model binder接口强制同步API…但通过将此代码移动到我的控制器中:

public async Task<IHttpActionResult> DoStuff()
{
    var json = await Request.Content.ReadAsStringAsync();
     ......
}
公共异步任务DoStuff()
{
var json=await Request.Content.ReadAsStringAsync();
......
}

使用wait over.Result进行消费-web请求顺利通过。我很好奇为什么?

如果在任务中使用Result,它将阻止当前正在执行的线程,直到它返回结果;如果等待调用,请求将异步运行,而不会阻止线程;并且可以使用wait运行多个请求(任务)函数,而不会阻止线程。
因此,最好使用wait而不是result。

result阻塞直到任务完成。不要使用它。