C# 如何在调度程序计时器内获取任务的结果?
我用以下方式定义了一个调度程序计时器:C# 如何在调度程序计时器内获取任务的结果?,c#,wpf,multithreading,C#,Wpf,Multithreading,我用以下方式定义了一个调度程序计时器: DispatcherTimer dispatcherTime; public AppStartup() { dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); dispatcherTimer.Interval = new TimeSpan(0, 0, 5); dispatch
DispatcherTimer dispatcherTime;
public AppStartup()
{
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
dispatcherTimer.Start();
}
在Tick事件中,我需要触发一个异步方法:
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
bool result = CheckServer().Result;
if(result)
{
//start the app
}
else
{
//display message server not available
}
}
问题是我得到了这个例外:
在System.Threading.Tasks.Task.ThrowifeExceptionalBoolean中包含TaskCanceledExceptions
在System.Threading.Tasks.Task1.GetResultCreboolean waitCompletionNotification中
在System.Threading.Tasks.Task1.get_结果中
在App.dispatchermer\u对象发送方中,事件参数e
在System.Windows.Threading.Dispatchermer.FireTickObject中未使用
在System.Windows.Threading.ExceptionWrapper.InternalRealCallDelegate回调中,对象args,Int32 numArgs
在System.Windows.Threading.ExceptionWrapper.TryCatchWhenObject源、委托回调、对象参数、Int32 numArgs、委托catchHandler中
CheckServer方法具有以下代码:
public async Task<bool> CheckServer()
{
bool result = false;
try
{
await AnotherMethod();
}
catch(Exception ex)
{
await this.ShowMessageAsync("attention", "an exception occurred: " + ex.message);
return false;
}
return result;
}
如何处理这种情况?将事件处理程序声明为异步并等待CheckServer任务:
private async void dispatcherTimer_Tick(object sender, EventArgs e)
{
bool result = await CheckServer();
...
}
编辑:可能会扔掉CheckServer方法,然后像这样编写勾号处理程序:
private async void dispatcherTimer_Tick(object sender, EventArgs e)
{
try
{
await AnotherMethod();
}
catch (Exception ex)
{
await ShowMessageAsync("attention", "an exception occurred: " + ex.message);
}
}
wait this.ShowMessageAsync的可能重复项这是什么?无论如何,您都不需要它,尤其是在WPF和数据绑定方面。充其量它将阻止UI线程,或引发跨线程访问异常。最坏的情况是它会导致死锁。使用IProgress