[英]How can I run a method without waiting for long running process
我有一个带有@RenderBody
节和一个index
页的Layout
。 我的索引页面运行时间很长,我希望它无需等待DoSomeAsyncStuff
即可呈现视图。 以下代码看起来很接近我想要的代码,但是问题出在我的模型上:传递给视图时,其属性为null:
public ActionResult Index()
{
MyModel model = new MyModel();
Task.Run(() => DoSomeAsyncStuff(model));
return View(model);
}
private async void DoSomeAsyncStuff(MyModel model)
{
await Task.Delay(20000);
model.Name = "Something";
//Assigning other model properties
}
在我看来,这里我得到NullReferenceException
并且Value cannot be null
错误,这肯定是因为DoSomeAsyncStuff
方法中仍然没有填充模型的属性:
<table>
<tr>
<th colspan="3">
@Model.Products.Select(c => c.Date).FirstOrDefault()
</th>
</tr>
@foreach (var item in Model.Products)
{
<tr>
<td>
@item.Title
</td>
<td>
@item.Price
</td>
</tr>
}
</table>
您尚未显示模型,因此这主要是伪代码。 首先,将长期运行的内容移至另一个操作:
public ActionResult Index()
{
var model = new MyModel();
return View(model);
}
public async Task<ActionResult> DoSomeAsyncStuff()
{
var model = new MyModel();
await Task.Delay(20000);
model.Name = "Something";
//Assigning other model properties
return PartialView("_InnerView", model);
}
与模型绑定的所有内容都应在局部视图中(在这里我称之为_InnerView.cshtml
)。 父视图应该仅具有一个占位符或加载小部件,该小部件或加载小部件当前与您的模型绑定的标记位于:
<div id="load-with-ajax">
Please wait. Loading...
</div>
然后,在页面的某处,在您的jQuery参考之后(我假设您正在使用jQuery或愿意使用),添加如下内容:
<script>
$(function(){
$('#load-with-ajax').load('@Url.Action("DoSomeAsyncStuff")');
});
</script>
您需要应用异步并等待您的方法。 这将确保在将模型传递到视图时填充该模型。
public async Task<ActionResult> Index()
{
var model = new MyModel();
await DoSomeAsyncStuff(model);
return View(model);
}
private async Task DoSomeAsyncStuff(MyModel model)
{
await Task.Delay(20000);
model.Name = "Something";
//Assigning other model properties
}
唯一的其他选择是在两个调用中执行此操作。
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> PartialIndex()
{
var model = new MyModel();
await DoSomethingAsync(model);
return PartialView(model);
}
private async Task DoSomeAsyncStuff()
{
await Task.Delay(20000);
model.Name = "Something";
//Assigning other model properties
}
为了确保填充模型,这两种方法都必须等待异步方法返回。 第二种方法可能会被调整为更接近您要查找的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.