如果 Task.run 可以实现同样的效果,为什么还要使用 async await

Why use async await if same can be achieved by Task.run

下面两种方法的行为是否相同?它们的工作方式是否存在内部差异?这两种方法都会释放 UI 线程并在延迟结束后继续执行。

    public async Task DoSomethingAsync()
    {
        Console.WriteLine("Test Async start");
        //Any long running operation
        await Task.Delay(5000);
        Console.WriteLine("Test Async end");
    }

    public void TestTask()
    {
        Console.WriteLine("Test Task start");

        Task.Run(() =>
            {    
                //Any long running operation                
                Thread.Sleep(10000);
            }
        ).ContinueWith((prevTask) =>
        {
            Console.WriteLine("Test Task end");
        });
    }

**output**:
Test Async start
Test Task start
Test Async end
Test Task end

Asynchronous programming with async and await

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.

您不需要 System.Threading 任务。下面的代码是因为 CancellationToken。

一个不同之处在于,对于 Task,您可以访问主 (UI) 线程上的属性。

查看数量。您甚至可以写入主线程,但可能不是一个好习惯。

    async Task<int> TaskDelayAsync(CancellationToken ct, IProgress<int> progress)
    {
        Debug.WriteLine(Quantity);
        int i = 0; 
        while (true)
        {               
            i++;
            //Debug.WriteLine(i);
            progress.Report(i);
            ct.ThrowIfCancellationRequested();
            await Task.Delay(500);
        }
        return i;
    }