如何在C#中返回请求之前等待HttpClient GetAsync调用

时间:2018-01-07 18:53:44

标签: c# httpclient getasync

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

        }
    }

1 个答案:

答案 0 :(得分:1)

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

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

无需在此处放置thread.sleep - 您已等待结果。