【问题标题】:How to wait for HttpClient GetAsync call until it returns the request in C#如何等待 HttpClient GetAsync 调用,直到它返回 C# 中的请求
【发布时间】:2018-01-09 04:10:40
【问题描述】:

我正在尝试通过 HttpClient 获取数据。数据大小不一,可能从几字节到兆字节不等。我注意到很多时候我的应用程序甚至在它从 GetAsync 返回之前就已经存在。我怎样才能等到 GetAsync 完成它的调用?从主应用程序:-

        backup.DoSaveAsync();
        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.BackgroundColor = ConsoleColor.Red;
        // My app exist by printing this msg, wihout getting any data. 
        // someitmes it gets data and other times it gets notinng.
        // I used sleep to wait to get the call completed. 
        Console.WriteLine("\nBackup has done successfully in SQL database")

        public async void DoSaveAsync()
        {
            using (var client = GetHttpClient(BaseAddress, path, ApiKey))
            {
                Stream snapshot = await  GetData(client, path);

                if (snapshot != Stream.Null)
                {
                    snapshot.Position = 0;
                    SaveSnapshot(snapshot);
                }
            }
        }

   private async Task<Stream> GetData(HttpClient client, string path)
    {
        HttpResponseMessage response = null;
        try
        {
            response = await client.GetAsync(path);
            System.Threading.Thread.Sleep(5000);
            if (response.IsSuccessStatusCode == false)
            {
                Console.WriteLine($"Failed to get snapshot");
                return Stream.Null;
            }
            return await response.Content.ReadAsStreamAsync();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return Stream.Null;
        }
    }

cmets 和答案后的代码更新:

     // in my main app, I have this code. 
     // How can I get the completed task or any error return by the task here.
    backup.DoBackupAsync().Wait();

    public async Task<Stream> DoSaveAsync()
    {
        using (var client = GetHttpClient(BaseAddress, SnapshotPath, ApiKey))
        {
            try
            {
                Stream snapshot = await GetSnapshot(client, SnapshotPath);

                if (snapshot != Stream.Null)
                {
                    snapshot.Position = 0;
                    SaveSnapshot(snapshot);
                }
                return snapshot;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }

        }
    }

【问题讨论】:

  • 你怎么称呼GetData
  • 调用GetData的代码在哪里?你为什么使用 Thread.Sleep(5000)?
  • 正确等待代码不会有您描述的行为。请发布真实的minimal reproducible example
  • 您在等待 GetData 的来电吗?
  • 请发布您的真实代码 - 不要删减。

标签: c# httpclient getasync


【解决方案1】:

由于该方法是异步的,backup.DoSaveAsync() 行只启动一个任务但不等待结果,因此您可以在任务完成之前调用Console.ReadLine(并可能退出您的程序)。您应该返回 Task 而不是 void - 使用 void 异步方法通常是不好的设计,并且您必须通过 await(如果您从异步方法调用)或通过 .Wait() 等待 backup.DoSaveAsync()

另外,如果GetData 出现错误,您不会为DoSaveAsync 返回任何错误 - 您可能想要处理这个问题,在当前代码中,您将打印“无法获取快照”,然后“备份已在 SQL 数据库中成功完成”。考虑不要在GetData 中使用Console.ReadLine 并在DoSaveAsync 中返回一个Task 表示成功

无需在此处输入thread.sleep - 您已经在等待结果了。

【讨论】:

  • 你能检查我更新的问题吗?然后回答我?
  • 使用Task myTask = backup.DoBackupAsync(),然后你可以使用myTask.Wait()myTask.Result(调用它也会等待任务——你必须调用其中一个来确保任务完成——或失败)和myTask.Status
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2020-07-22
  • 2022-09-27
  • 1970-01-01
相关资源
最近更新 更多