哪些ASP.NET生命周期事件可以异步?

前端之家收集整理的这篇文章主要介绍了哪些ASP.NET生命周期事件可以异步?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写了一个自定义的ASP.NET控件,我只是更新它有一个异步加载事件处理程序。现在我得到这个错误

An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page,ensure that the Page is marked <%@ Page Async=”true” %>.

页面具有<%@ Page Async =“true”%>标签。所以我认为控件不能有异步加载事件处理程序。

在哪里可以找到允许异步的ASP.NET Webforms生命周期中的事件的完整列表?

解决方法

来自ASP.NET团队的Damian Edwards给出了这个答案:

Async void event handlers in web forms are only supported on certain
events,as you’ve found,but are really only intended for simplistic
tasks. We recommend using PageAsyncTask for any async work of any real
complexity.

来自ASP.NET团队的Levi Broderick给出了这个答案:

Async events in web applications are inherently strange beasts. Async
void is meant for a fire and forget programming model. This works in
Windows UI applications since the application sticks around until the
OS kills it,so whenever the async callback runs there is guaranteed
to be a UI thread that it can interact with. In web applications,
this model falls apart since requests are by definition transient. If
the async callback happens to run after the request has finished,
there is no guarantee that the data structures the callback needs to
interact with are still in a good state. Thus why fire and forget
(and async void) is inherently a bad idea in web applications.

That
said,we do crazy gymnastics to try to make very simple things like
Page_Load work,but the code to support this is extremely complicated
and not well-tested for anything beyond basic scenarios. So if you
need reliability I’d stick with RegisterAsyncTask.

所以我认为我的问题的答案是:“这是错误的问题。

正确的问题是“我应该如何异步在我的ASP.NET Web窗体应用程序?答案是将此代码段插入到您的aspx代码隐藏文件中:

this.RegisterAsyncTask(new PageAsyncTask(async cancellationToken => {
    var result = await SomeOperationAsync(cancellationToken);
    // do something with result.
}));

这个相同的技巧在ASP.NET自定义控件中工作,只是使用this.Page.RegisterAsyncTask。

猜你在找的asp.Net相关文章