Reputation: 25
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.Task
1.GetResultCore(Boolean waitCompletionNotification) in System.Threading.Tasks.Task
1.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?
Upvotes: 0
Views: 1103
Reputation: 128061
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);
}
}
Upvotes: 1