我有一个方法
public void AddOrUpdateAnswer ( AnswerSubmission Answer, Guid pid )
{
this._Conn.Open();
using (SqlCommand cmd = new SqlCommand("AddOrUpdateAnswer", this._Conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@AnswerVal", Answer.AnswerVal);
cmd.Parameters.AddWithValue("@QuestionId", Answer.QuestionId);
cmd.Parameters.AddWithValue("@PartnerId", pid);
cmd.ExecuteNonQuery();
}
this._Conn.Close();
}
我需要将其转换为异步任务,因为每当我有多个用户主动提交答案时,我发现它崩溃了我的网络应用程序(502 Bad Gateway)。所以我知道我需要做的就是让这个东西成为异步方法。目前,它由我的控制器调用,如
[HttpPost]
public ActionResult SubmitAnswer ( AnswerSubmission Answer, Guid pid)
{
bool goodSoFar = true;
string status = "Answers submitted successfully";
try
{
this._Db.AddOrUpdateAnswer(Answer, pid);
}
catch (Exception e)
{
goodSoFar = false;
status = String.Format("Exception occured during answer submission: {0}", e.Message);
}
return Json(new { Succeeded = goodSoFar, Message = status });
}
所以我认为我需要做的就是做到这一点 像
[HttpPost]
public async Task<ActionResult> SubmitAnswer ( AnswerSubmission Answer, Guid pid)
{
bool goodSoFar = true;
string status = "Answers submitted successfully";
try
{
await this._Db.AddOrUpdateAnswer(Answer, pid);
}
catch (Exception e)
{
goodSoFar = false;
status = String.Format("Exception occured during answer submission: {0}", e.Message);
}
return Json(new { Succeeded = goodSoFar, Message = status });
}
但是我该如何处理AddOrUpdateAnswer
?我尝试将其更改为
public Task AddOrUpdateAnswer
但后来我得到的错误是并非所有路径都返回一个值。我应该回来什么?
答案 0 :(得分:0)
您只需将方法转换为异步:
public async Task AddOrUpdateAnswerAsync ( AnswerSubmission Answer, Guid pid )
{
await this._Conn.OpenAsync();
using (SqlCommand cmd = new SqlCommand("AddOrUpdateAnswer", this._Conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@AnswerVal", Answer.AnswerVal);
cmd.Parameters.AddWithValue("@QuestionId", Answer.QuestionId);
cmd.Parameters.AddWithValue("@PartnerId", pid);
await cmd.ExecuteNonQueryAsync();
}
this._Conn.Close();
}
查看here了解更多详情