【发布时间】:2019-04-08 20:30:43
【问题描述】:
我有一个控制台程序,它将异步 HTTP 请求发送到外部 Web API。 (HttpClient.GetAsync());)
这些任务可能需要几分钟才能完成 - 在此期间我希望能够向用户显示应用仍在运行 - 例如每 10 秒发送一次Console.WriteLine("I ain't dead - yet")。
我不知道如何正确地做,没有隐藏异常、引入死锁等的风险。
我知道 IProgress
还有: 我无法将 GUI 设置为“InProgress”,因为没有 GUI,它是一个控制台应用程序 - 如果我不时不时发送更新消息,用户似乎会停止工作。
目前的想法:
try
{
var task = httpClient.GetAsync(uri); //actually this is an SDK method call (which I cannot control and which does not report progress itself)
while (!task.IsCompleted)
{
await Task.Delay(1000 * 10);
this.Logger.Log(Verbosity.Verbose, "Waiting for reply...");
}
onSuccessCallback(task.Result);
}
catch (Exception ex)
{
if (onErrorCallback == null)
{
throw this.Logger.Error(this.GetProperException(ex, caller));
}
this.Logger.Log(Verbosity.Error, $"An error when executing command [{action?.Command}] on {typeof(T).Name}", ex);
onErrorCallback(this.GetProperException(ex, caller));
}
【问题讨论】:
-
你不能
await说await action.Action() -
@Rahul - 当然,但这样我会等待 5 分钟,而没有用户信息...
-
实施 IProgress 怎么样? blogs.msdn.microsoft.com/dotnet/2012/06/06/…
-
@Fildor 实际上我会做相反的事情,我会将
Timer重构为上面的代码。原因是上面的代码可以在 WinForms、WPF 和控制台中正常工作,因为上面的代码使用了SynchronizationContext.Current。
标签: c# asynchronous async-await progress