0
votes

I have a Dispatcher Timer defined in the following way:

DispatcherTimer dispatcherTime;

public AppStartup()
{
   dispatcherTimer = new DispatcherTimer();
   dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
   dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
   dispatcherTimer.Start();
}

inside the Tick event I need to fire an async method:

 private void dispatcherTimer_Tick(object sender, EventArgs e)
 {
     bool result = CheckServer().Result;

     if(result)
     {
        //start the app
     }
     else 
     {
        //display message server not available
     }
}

the problem's that I get this exception:

in System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) in System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) in System.Threading.Tasks.Task1.get_Result() in App.dispatcherTimer_Tick(Object sender, EventArgs e) in System.Windows.Threading.DispatcherTimer.FireTick(Object unused) in System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) in System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)

the method CheckServer have this code:

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;
}

how can I manage this situation?

1
await this.ShowMessageAsync what is this? You don't need it anyway, especially with WPF and data binding. At best it will block the UI thread, or throw a cross-thread access exception. Worst case it will cause a deadlock. Use IProgress< T> to report events, don't try to access the UI thread from a background threadPanagiotis Kanavos
@PanagiotisKanavos the ShowMessageAsync is provided by MahApp framework which must be declared with the awaitIl Ragazzo Di Campagna

1 Answers

1
votes

Declare the event handler async and await the CheckServer Task:

private async void dispatcherTimer_Tick(object sender, EventArgs e)
{
    bool result = await CheckServer();

    ...
}

Edit: Probably throw away the CheckServer method and write the Tick handler like this:

private async void dispatcherTimer_Tick(object sender, EventArgs e)
{
    try
    {
        await AnotherMethod();
    }
    catch (Exception ex)
    {
        await ShowMessageAsync("attention", "an exception occurred: " + ex.message);
    }
 }