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报告事件,不要尝试从后台访问UI线程thread@PanagiotisKanavosShowMessageAsync是由MahApp框架提供的,它必须在waitthe异常消失的情况下声明,但是现在当到达这一行时,我得到了null引用异常:waitit this.ShowMessageAsyncattention,发生异常:+ex.message;为什么?@IlRagazzoDiCampagna,因为您正在尝试访问ShowMessageAsync中的UI线程。不要。使用IProgress界面报告进度或errors@IlRagazzoDiCampagna也张贴代码ShowMessageAsync@IlRagazzoDiCampagna顺便说一句,您甚至不应该尝试在CheckServer中处理execptions,让Tick处理程序来处理,并显示一个顶级警告窗口,而不是一个阻塞消息框