简体   繁体   English

了解基于任务的异步模式C#

[英]Understanding Task based asynchronous pattern C#

I am starting to study C# TAP coding. 我开始学习C#TAP编码。 I don't understand why the code is running synchronously 我不明白为什么代码会同步运行

    async private void timer1_Tick(object sender, EventArgs e)
    {
        SyncCount++;
        result1.Text = SyncCount.ToString();

        AsyncCount = await CountForALongTimeAsync(AsyncCount);
        result2.Text = AsyncCount.ToString();
    }

    async Task<int> CountForALongTimeAsync(int counter)
    {
        Thread.Sleep(3000);
        counter++;
        return counter;
    }
async Task<int> CountForALongTimeAsync(int counter)
{

What comes next will be executed until the first await ed async call that actually does some waiting (it's possible that a given call could have all it needs to return immediately, eg a service that might hit the internet or might return data from a cache, in which case it won't wait). 接下来执行的操作将一直执行到第一个await异步调用,该调用实际上会进行一些等待(给定的调用可能具有立即返回的所有条件,例如,可能会访问Internet的服务或可能会从缓存返回数据的服务,在这种情况下,它不会等待)。

There are no await ed calls at all, so the Task returned is returned already completed. 根本没有await调用,因此返回的Task已经完成返回。

Since the calling await CountForALongTimeAsync is await ing a task that is returned already completed, it runs synchronously. 由于调用await CountForALongTimeAsync正在await返回已完成的任务,因此它将同步运行。

The method would be better as: 该方法将更好,因为:

async Task<int> CountForALongTimeAsync(int counter)
{
    await Task.Delay(3000);
    counter++;
    return counter;
}

Incidentally, the pre await way of doing something very (but not entirely) similar would have been: 顺便说一句,做(非常不完全)相似的事情的await方式是:

Task<int> CountForALongTimeAsync(int counter)
{
    return Task.Delay(3000).ContinueWith(t =>
    {
        ++counter;
        return counter;
    });
}

Considering that these are different ideas of "continuing" after a task might or might not give some insight. 考虑到这些是在任务执行后“继续”的不同想法,可能会或可能不会提供某些见解。

In contrast the closest pre-await way of doing what the code in your question does was: 相反,执行问题代码的最接近的等待方式是:

Task<int> CountForALongTimeAsync(int counter)
{
    Thread.Sleep(3000);
    counter++;
    return Task.FromResult(counter); //FromResult returns an already completed task.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM