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