我正在使用异步任务来返回我使用数据字典建模的Json数据。我希望任务在从我的方法report.GetActiveBuildDefinitions()
和我的CurrentState对象中调用数据时异步执行,该对象具有获取我需要的数据的构造函数。这是我正在谈论的构造函数 - > new CurrentState(BuildDef.ID);
该控制器功能正常。但是当我启用警告为错误时。我的课没有建立。它要求我为异步任务使用await关键字。我尝试将其添加到return await Json(state);
之类的返回中,但是它会给出一个错误,"不包含getawaiter的定义"请帮忙
这是我的控制者:
[HttpGet]
public async Task<IHttpActionResult> GetBuildState()
{
try
{
List<CurrentState> state = new List<CurrentState>();
BuildReport report = new BuildReport();
List<BuildDefinition> definitions = report.GetActiveBuildDefinitions();
List<Dictionary<string, string>> buildInfo = new List<Dictionary<string, string>>();
foreach (BuildDefinition BuildDef in definitions)
{
state.Add(new CurrentState(BuildDef.ID));
}
foreach (CurrentState build in state)
{
Dictionary <string, string> entry = new Dictionary<string, string>();
if (build.ITestExists)
{
if (build.ITestState && build.BuildState)
{
entry.Add("BuildDef", build.BuildDefName);
entry.Add("GraphCode", "1");
entry.Add("WorkingBrokenTime", GetTime(build.BuildDefID));
entry.Add("Icon", "1");
entry.Add("Id", build.BuildDefID.ToString());
}
else if(build.BuildState && build.ITestState.Equals(false))
{
entry.Add("BuildDef", build.BuildDefName);
entry.Add("GraphCode", "2");
entry.Add("WorkingBrokenTime", GetTime(build.BuildDefID));
entry.Add("Icon", "0");
entry.Add("Id", build.BuildDefID.ToString());
}
else if (build.BuildState.Equals(false) && build.ITestState)
{
entry.Add("BuildDef", build.BuildDefName);
entry.Add("GraphCode", "3");
entry.Add("WorkingBrokenTime", GetTime(build.BuildDefID));
entry.Add("Icon", "0");
entry.Add("Id", build.BuildDefID.ToString());
}
else if (build.ITestState.Equals(false) && build.BuildState.Equals(false))
{
entry.Add("BuildDef", build.BuildDefName);
entry.Add("GraphCode", "0");
entry.Add("WorkingBrokenTime", GetTime(build.BuildDefID));
entry.Add("Icon", "0");
entry.Add("Id", build.BuildDefID.ToString());
}
}
else
{
if (build.BuildState)
{
entry.Add("BuildDef", build.BuildDefName);
entry.Add("GraphCode", "4");
entry.Add("WorkingBrokenTime", GetTime(build.BuildDefID));
entry.Add("Icon", "1");
entry.Add("Id", build.BuildDefID.ToString());
}
else
{
entry.Add("BuildDef", build.BuildDefName);
entry.Add("GraphCode", "5");
entry.Add("WorkingBrokenTime", GetTime(build.BuildDefID));
entry.Add("Icon", "0");
entry.Add("Id", build.BuildDefID.ToString());
}
}
buildInfo.Add(entry);
}
return Json(state);
}
catch (Exception)
{
return BadRequest(ModelState);
}
}
答案 0 :(得分:1)
我希望任务以异步方式执行
但为什么呢?你觉得异步会给你带来什么好处呢?
提示:async
不意味着“早退”。
当前控制器操作中的所有内容都是同步的,因此您的控制器操作也应该是同步的:
public IHttpActionResult GetBuildState()
现在,如果您将I / O调用更改为自然异步(即使用EF6异步查询),那么您的控制器操作最终可能会调用异步方法:
var definitions = await report.GetActiveBuildDefinitionsAsync();
并且此时,编译器将告诉您使GetBuildState
异步并将其返回类型更改为Task<IHttpActionResult>
。