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阻塞直到任务完成。不要使用它。