如何等待 HttpClient GetAsync 调用,直到它在 C# 中返回请求



我正在尝试通过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;
        }
    }

注释和回答后的代码更新:

     // 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;
            }
        }
    }

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

此外,如果 GetData 中出现错误,您不会返回任何错误DoSaveAsync - 您可能需要处理此问题,在当前代码中,您将打印"无法获取快照",然后打印"备份已在 SQL 数据库中成功完成"。考虑在GetData中不使用 Console.ReadLine,并在指示成功的DoSaveAsync中返回任务

无需在这里放thread.sleep - 您已经在等待结果。

最新更新