我正在尝试在MVC6中实现一个异步组件,并且我正在努力解决这个问题。
查看代码:
@await Component.InvokeAsync("GetTextA")
@Component.Invoke("GetTextB")组件A代码:
public class GetTextAViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
await Task.Delay(12000);
return View("Default","from code");
}
}组件B代码:
public class GetTextBViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
return View("Default");
}
}加载视图的时间超过12000毫秒。这意味着异步组件被同步加载。
如何使其异步加载,以便在不等待异步组件的情况下加载视图中的所有内容。
发布于 2015-05-05 02:43:27
如果您希望呈现视图并在稍后运行异步代码,则基本上必须使用Ajax。运行组件异步意味着它不会阻塞线程,它可以被其他请求重用。
编辑:如果您想呈现页面的顶部,并让其余部分稍后显示,您可以使用新的@Flush功能。在长时间运行的任务之前添加对@await FlushAsync()的调用,视图顶部将刷新到客户端。如果你使用的是布局,它会变得有点复杂,遵循下面的测试可以获得更多的例子:
发布于 2016-06-14 20:59:34
在下面的示例中,您可以看到,尽管两个组件都有6秒的延迟,但呈现响应并不需要12秒。这证明,视图组件可以异步调用,这有效地节省了CPU时钟周期,并使其服务于比以往更多的并发请求。
AViewComponent
public async Task<IViewComponentResult> InvokeAsync()
{
await Task.Delay(6000);
return View<string>("Hello World A!");
}BViewComponent
public async Task<IViewComponentResult> InvokeAsync()
{
await Task.Delay(6000);
return View<string>("Hello World B!");
}Views\Shared\Components\A\Default.cshtml
@model string
<h1>@Model</h1>Views\Shared\Components\B\Default.cshtml
@model string
<h1>@Model</h1>index.cshtml
@DateTime.Now
@{
var taskA = Component.InvokeAsync("A");
var taskB = Component.InvokeAsync("B");
taskA.Wait();
taskB.Wait();
}
@taskA.Result
@taskB.Result
@DateTime.Now输出(见6秒的时间差)
6/14/2016 6:09:04 PM
Hello World A!
Hello World B!
6/14/2016 6:09:10 PM
https://stackoverflow.com/questions/30037522
复制相似问题