Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async GUI using WebForms and .NET 4.5 await/async

I've been looking for any simple example building async interfaces using ASP.NET WebForms. That is when an async method is done the await shall render.

This is one of the examples I've been looking at, How and When to use `async` and `await`. The implementation I've been looking for would look something like this

protected async void button1_Click(object sender, EventArgs e)
{
    // Render when done
    textBox1.Text += await WaitAsynchronouslyAsync(RandomNumber(2000, 4000));

    // Render when done
    textBox1.Text += await WaitAsynchronouslyAsync(RandomNumber(100, 1000));
}

public async Task<string> WaitAsynchronouslyAsync(int delay)
{
    await Task.Delay(delay);
    return string.Concat(delay, "; ");
}
private int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}

This will however always render when everything is done, but at the same time. In the example above the desired result would be the second call to WaitAsynchronouslyAsync to render before the first call since it always will be less delay.

Or is it even possible using webforms? I do know how to do this in JavaScript using webapi's, websockets and whatnot and that's not the solution I desire at the moment.

like image 258
Eric Herlitz Avatar asked May 26 '26 16:05

Eric Herlitz


1 Answers

As I describe on my blog, async does not change the HTTP protocol.

HTTP provides you with one response for each request. So, when an HTTP request arrives, it must execute your page to completion before sending the response.

In the ASP.NET world, await does not yield to the client/browser. Instead, it yields to the ASP.NET runtime. ASP.NET will not send the response until it sees that your processing is all done.

If you want to dynamically update a page (or partially render one), then you'll need to do it yourself using an appropriate technology (SignalR, UpdatePanel, etc).

like image 158
Stephen Cleary Avatar answered May 30 '26 07:05

Stephen Cleary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!