简体   繁体   中英

Can't run task async in ASP.NET Webforms

I'm trying to create an asynchronous task in ASP.NET Webforms. After studying the various sources from the Internet, I created this:

Default.aspx:

namespace AsyncTestCs
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterAsyncTask(new PageAsyncTask(LoadSomeData));
        }

        public async Task LoadSomeData()
        {
            var downloadedString = await new WebClient().DownloadStringTaskAsync("http://localhost:59850/WebForm1.aspx");

            Label1.Text = downloadedString;
        }
    }
}

WebForm1.aspx:

namespace AsyncTestCs
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Thread.Sleep(5000);
            Response.Write("something");
        }
    }
}

but it does not work asynchronously. This page will be displayed after it loads downloadedString.

Where is my mistake?

Your server code is not "attached" to the controls on the client. ASP.NET generates HTML as part of its processing and sends it to the client. After that all ASP.NET objects associated with the request die. HTTP is request-response based. There is no permanent connection.

What you're doing here is wait 5sec, then configure the label text, then send HTML with that label text to the client.

Async has nothing to do with delayed updates to the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM