我正试图通过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;
}
}
}
发布于 2018-01-07 21:17:37
由于方法是异步的,backup.DoSaveAsync()
行只启动一个任务,而不等待结果,因此您可以在任务完成之前调用Console.ReadLine
(并可能退出程序)。您应该返回Task
而不是void
--通常情况下,使用void异步方法是不好的设计,而年轻用户必须通过等待(如果从异步方法调用),或者通过.Wait()
等待backup.DoSaveAsync()
。
此外,在GetData
中出现错误时,您不会返回DoSaveAsync
的任何错误--您可能想要处理这个错误,在当前代码中,您将打印“未能获得快照”,然后“备份已在SQL数据库中成功完成”。考虑不要在Console.ReadLine中使用GetData
,并在DoSaveAsync
中返回一个表示成功的任务
不需要在这里放置thread.sleep
--你已经在等待结果了。
https://stackoverflow.com/questions/48140488
复制相似问题