【发布时间】:2014-04-16 19:59:12
【问题描述】:
我有一个返回 JSON 结果的控制器操作方法。 在这个控制器动作中,我想做 asyc 并等待一个长时间运行的操作,而不是等待 JSON 结果返回到浏览器。
我有以下示例代码 -
`public JsonResult GetAjaxResultContent(string id)
{
List<TreeViewItemModel> items = Test();
//use the below long running method to do async and await operation.
CallLongRunningMethod();
//i want this to be returned below and not wait for long running operation to complete
return Json(items, JsonRequestBehavior.AllowGet);
}
private static async void CallLongRunningMethod()
{
string result = await LongRunningMethodAsync("World");
}
private static Task<string> LongRunningMethodAsync(string message)
{
return Task.Run<string>(() => LongRunningMethod(message));
}
private static string LongRunningMethod(string message)
{
for (long i = 1; i < 10000000000; i++)
{
}
return "Hello " + message;
}
`
但是,控制器操作会一直等待,直到它完成长时间运行的方法,然后返回 json 结果。
【问题讨论】:
-
...所以不要等待它?只需启动一项任务...
-
@SimonWhitehead 不负责任的回答。根据 Nisd 的描述,这可能会导致问题。如果客户端 javascript 发送另一个请求来启动长期存在的过程,那就更好了。 IIS
-
@Aron 这不是一个答案.. 这是一个评论 :) 我知道这些陷阱 - 但是,问题是它是什么,我怀疑这是“关键任务" 到 OP 的业务。
标签: c# asp.net-mvc async-await