简体   繁体   中英

await Task.Delay(0) Runs OK but await Task.Delay(1000) Does not

I am trying to implement async using Visual Studio 2017. Being new to async, here is my first attempt, which I cannot get to work and also cannot find the answer anywhere on the internet.

await Task.Delay(any non-zero number) appears to be in an infinite loop.
await Task.Delay(0) executes properly.

What am I missing?

using System;
using System.Threading.Tasks;
using System.Web.UI;

namespace TestAsync
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterAsyncTask(new PageAsyncTask(GetContentAsync)); //It doesn't seem to matter whether I have this statement or not.
            var contentTask = GetContentAsync();
            Label1.Text = "This is now";
            Label2.Text = contentTask.Result.ToString();
        }

        public async Task<string> GetContentAsync()
        {
            await Task.Delay(0);  //Any non-zero number appears to cause an infinite loop.
            return "That's all folks";
        }
    }
}

You are experiencing a deadlock due to blocking on async code with the call to the Task's Result property.

One way implement your page load in this case is as an async void method, then using await on your method. Using async void does have some unsavory consequences, however.

protected async void Page_Load(object sender, EventArgs e)
{
    Label1.Text = "This is now";
    Label2.Text = await GetContentAsync();
}

You can now use a non-zero value in your Task.Delay without the deadlock occurring.

Using async void isn't generally advisable. You should instead register a task in your page load method, then handle the setting of your label within that. Something like this could do the trick:

protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(SetContentAsync));
    Label1.Text = "This is now";
}

private async Task SetContentAsync() 
{
    Label2.Text = await GetContentAsync();
}

Microsoft has an additional article on using async/await within webforms which I would recommend giving a read. You can find it here .

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