Display string async with delay

I am trying to display a string in a web page with delay and the following is what I tried but the page does not show until the delay is expired.

protected void Page_Load(object sender, EventArgs e)
{
    Print().GetAwaiter().GetResult();
}

private async Task Print()
{
    await Task.Run(async () =>
    {
        await Task.Delay(10000);
        pr.InnerText = "this is a test...";
    });
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

What you wrote is synchronous code, the “correct” way is simply:

protected async void Page_Load(object sender, EventArgs e)
{
    await Task.Delay(10000);
    pr.InnerText = "this is a test...";
}

However, this won’t solve your issue. You added a delay on the server-side code generation, so all you’ve succeeded is to wait longer until everything appears on the client-side. You should look into AJAX calls to load your data asynchronously on the client side, and send the whole page framework as soon as possible from the server side.

Edit: alternatively, use a modern framework like Blazor, where something like this would work. WebForms has been dead for over 10 years.

Method 2

I would recommend removing this delay from the backend and on the front end use javascript to to asynchronously call the back end for the string. You can use setTimeout and ajax post to accomplish this.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x