异步方法在 C# 中是如何工作的?

问题描述 投票:0回答:0

BlobService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AllAboutAsyncProgramming.services
{
    public class BlobService
    {
        public async Task<string> GetBlobAsync()
        {
            Console.WriteLine($"GetBlobAsync - {Environment.CurrentManagedThreadId}");

            HttpClient client = new HttpClient();

            var result = await client.GetAsync("https://www.google.com");

            Console.WriteLine($"GetBlobAsync - {Environment.CurrentManagedThreadId}");

            return result.ToString();
        }
    }
}

Program.cs

using AllAboutAsyncProgramming.services;

class Program
{
    public static async Task Main(string[] args)
    {
        BlobService blobService = new BlobService();
        
        Console.WriteLine($"Main - {Environment.CurrentManagedThreadId}");

        var x = await blobService.GetBlobAsync();

        Console.WriteLine($"Main - {Environment.CurrentManagedThreadId}");
    }
}

结果

例子 - 1

Main - 1
GetBlobAsync - 1
GetBlobAsync - 6
Main - 6

示例 - 2(另一次运行)

Main - 1
GetBlobAsync - 1
GetBlobAsync - 9
Main - 9

结果总是这样。前两行输出获得相同的线程 ID,底部两行输出始终获得相同的线程 ID。 (如结果部分所示)

当它执行这行代码时 -->

var x = await blobService.GetBlobAsync();
是不是
GetBlobAsync
方法应该在单独的线程上运行?但它会打印主线程 ID。在
await
方法内调用
GetBlobAsync
之后 -->
await client.GetAsync("https://www.google.com");
它在单独的线程上运行。

我对执行流程感到困惑。怎么运行的?当我们等待某些东西时,它不应该在一个单独的线程上运行吗?

c# multithreading asynchronous async-await task
© www.soinside.com 2019 - 2024. All rights reserved.