如何在不等待长时间运行的过程的情况下运行方法 [英] How can I run a method without waiting for long running process

查看:95
本文介绍了如何在不等待长时间运行的过程的情况下运行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Layout,其中有一个@RenderBody部分和一个index页面.我的索引页运行时间很长,我希望它无需等待DoSomeAsyncStuff就可以呈现视图.下面的代码看起来很接近我想要的代码,但是问题出在我的模型上,当传递给视图时,它的属性为null:

I have a Layout with a @RenderBody section and an index page. My index page has a long running process and I want it renders the view without waiting for DoSomeAsyncStuff. The following code looks close to what I want but the problem is with my model that it's properties are null when pass to view:

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
}

在我看来,我得到NullReferenceExceptionValue cannot be null错误,这肯定是因为我的模型属性仍未填充在DoSomeAsyncStuff方法中:

Here in my view I get NullReferenceException and Value cannot be null errors and certainly it is because my model's properties are not still filled in the DoSomeAsyncStuff method:

<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>

推荐答案

您尚未显示模型,因此这大部分是伪代码.首先,将长期运行的内容移至另一个动作:

You haven't shown your model, so this will be mostly pseudo-code. First, move the long-running stuff to another action:

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).父视图应该只包含一个占位符或加载小部件,您的模型绑定标记当前位于该位置:

Everything that is model-bound should be in the partial view (what I'm calling _InnerView.cshtml, here). The parent view should just have a placeholder or loading widget where your model-bound markup currently resides:

<div id="load-with-ajax">
    Please wait. Loading...
</div>

然后,在页面的某处,在您的jQuery引用之后(假设您正在使用jQuery或愿意使用jQuery),添加以下内容:

Then, somewhere in the page, after your jQuery reference (I'm assuming you're using jQuery or are willing to), add something like:

<script>
    $(function(){
        $('#load-with-ajax').load('@Url.Action("DoSomeAsyncStuff")');
    });
</script>

这篇关于如何在不等待长时间运行的过程的情况下运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆