开发者

ASP.Net Async Page with Action.BeginInvoke

开发者 https://www.devze.com 2023-04-12 08:05 出处:网络
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.

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


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.

Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.

Source: ASP.NET Session State Overview, my highlight.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号