Async GUI using WebForms and .NET 4.5 await / asynchronous

I've been looking for any simple example of building asynchronous interfaces using ASP.NET WebForms. That is, when a async

method is executed await

, it must do.

This is one of the examples I looked at, How and when to use `async` and` await` . The implementation I was 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 always be displayed when everything is done, but at the same time. In the example above, the desired result would be a second call WaitAsynchronouslyAsync

to render before the first call, as it will always be less than the delay.

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

+3


source to share


2 answers


As I describe in my blog, async

does not change the HTTP protocol
.

HTTP provides you with one response for each request. So when an HTTP request comes in, it must execute your page before it finishes sending the response.



In the world ASP.NET await

is on par with client / browser. Instead, it results in the ASP.NET runtime. ASP.NET will not send a response until it sees that your processing is complete.

If you want to dynamically update the page (or partially execute it), you need to do it yourself using the appropriate technology (SignalR, UpdatePanel, etc.).

+2


source


When you use await

it the way you did it, the flow of execution is sequential. The first await

, and only after completion will the second be executed await

.

If you want them to run at the same time, you can initiate both operations and use Task.WhenAny

and assign a value to the one that ends up first:



Task<string> slowerTask = WaitAsynchronouslyAsync(RandomNumber(2000, 4000));
Task<string> fasterTask = WaitAsynchronouslyAsync(RandomNumber(100, 1000));

List<Task<string>> tasks = new List<Task<string>> { slowerTask, fasterTask };

while (tasks.Count > 0)
{
     Task<string> finishedTask = await Task.WhenAny(tasks);
     tasks.Remove(finishedTask);

     textBox1.Text = await finishedTask;
}

      

+1


source







All Articles