Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用HttpClient.GetAsync的块不注册取消令牌_C#_.net Core_Cancellation Token - Fatal编程技术网

C# 使用HttpClient.GetAsync的块不注册取消令牌

C# 使用HttpClient.GetAsync的块不注册取消令牌,c#,.net-core,cancellation-token,C#,.net Core,Cancellation Token,我注意到在HttpClient.GetAsync()的using块中尝试使用取消令牌时出现了意外行为 即,调用cancellationTokenSource.Cancel()不会触发此块内的取消令牌 据我所知,这段代码应该抛出OperationCancelledException并写出“TokenCancelled”,但它没有。有人知道为什么吗 static void Main(string[] args) { using (var client = new Ht

我注意到在HttpClient.GetAsync()的using块中尝试使用取消令牌时出现了意外行为

即,调用cancellationTokenSource.Cancel()不会触发此块内的取消令牌

据我所知,这段代码应该抛出OperationCancelledException并写出“TokenCancelled”,但它没有。有人知道为什么吗

    static void Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            var tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;

            Task.Run(async () =>
            {
                using (var response = await client.GetAsync("some_url"))
                {
                    try
                    {
                        while (true)
                        {
                            token.ThrowIfCancellationRequested();
                        }
                    }
                    catch (OperationCanceledException ex)
                    {
                        Console.WriteLine("Token cancelled");
                    }
                }
            });

            tokenSource.Cancel();
            Console.ReadKey();
        }
    }

可能任务在启动之前就被取消了。GetAsync会引发异常吗?旁注:不要在使用
块的
中使用
HttpClient
本身。我打赌
client.GetAsync
方法会引发异常。由于
Task.Run
不等待,因此此异常被忽略。