Earlgray
Earlgray

Reputation: 647

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?

Upvotes: 3

Views: 1132

Answers (1)

usr
usr

Reputation: 171178

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.

Upvotes: 2

Related Questions