带有 Action.BeginInvoke 的 ASP.Net 异步页面
我正在尝试在 asp .net 中编写一个异步页面,该页面在不同的线程中运行一个函数。 以下代码中的问题是,当我调试它时,函数 EndAsyncOperation 永远不会被调用。因此,页面不会完全加载并永远加载。 我使用 Action 在线程池中的不同线程中运行代码。是否有另一种方法可以在不同的线程中运行代码?
我哪里错了?
还有一个问题。我读到,在 ASP .Net 中,页面是使用线程池运行的。那么当我调试我的网站并尝试一起加载几个页面时,为什么它们会一个接一个地同步加载呢?
public partial class AsyncPage : System.Web.UI.Page
{
void Page_Load(object sender, EventArgs e)
{
AddOnPreRenderCompleteAsync(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation)
);
}
IAsyncResult BeginAsyncOperation(object sender, EventArgs e,
AsyncCallback cb, object state)
{
Action action = () =>
{
Start();
};
IAsyncResult asyncResult = action.BeginInvoke(new AsyncCallback(action.EndInvoke), null);
return asyncResult;
}
void EndAsyncOperation(IAsyncResult ar)
{
// This function isn't reached
}
public void Start()
{
// Do something
}
}
I'm trying to write an async page in asp .net which runs a function in a different thread.
The problem in the following code, is that when I debug it, the function EndAsyncOperation is never called. As a result, the page isn't fully loaded and loads for ever.
I use Action to run the code in a different thread from the thread pool. Is there maybe another way of running the code in a different thread that works?
Where am I going wrong?
And another question. I read that in ASP .Net the pages are ran with a threadpool. So howcome when I debug my site and try to load a few pages together they are loaded one after another syncronously?
public partial class AsyncPage : System.Web.UI.Page
{
void Page_Load(object sender, EventArgs e)
{
AddOnPreRenderCompleteAsync(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation)
);
}
IAsyncResult BeginAsyncOperation(object sender, EventArgs e,
AsyncCallback cb, object state)
{
Action action = () =>
{
Start();
};
IAsyncResult asyncResult = action.BeginInvoke(new AsyncCallback(action.EndInvoke), null);
return asyncResult;
}
void EndAsyncOperation(IAsyncResult ar)
{
// This function isn't reached
}
public void Start()
{
// Do something
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您需要将 BeginAsyncOperation 方法参数中提供给您的 AsyncCallback 对象传递给 BeginInvoke,而不是创建一个新的。
由于您的会话配置,您的页面正在同步加载。
来源:ASP.NET 会话状态概述,我的重点。
I believe that you need to pass the AsyncCallback object provided to you in the BeginAsyncOperation method parameters to BeginInvoke, not create a new one.
Your pages are loading synchronously because of your session configuration.
Source: ASP.NET Session State Overview, my highlight.