I have a timer setup in my mainwindow code behind that fires every ten seconds. Because some of the code referenced in the timer_Elapsed event is somewhat CPU intensive I have placed it inside an await Task.Run(() =>
, however the UI thread continues to hang momentarily whenever the elapsed event runs. Any ideas why this would be blocking the UI? Code:
async void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
await Task.Run(() =>
{
//Update default status bar text routinely
try
{
if (ChecEnabled())
{
this.Dispatcher.Invoke(() =>
{
StatusText.Text = String.Format("Status: Enabled. Watching for changes…");
});
}
else
{
this.Dispatcher.Invoke(() =>
{
StatusText.Text = String.Format("Status: Disabled");
});
}
}
catch (ObjectDisposedException)
{
//Window closed and disposed timer on different thread
}
//System Checks
UpdateSystemReadyStatus();
});
}
Update your Invoke
to InvokeAsync
. Also, do you really need to entire method wrapped in a Task
?
async void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
//Update default status bar text routinely
try
{
if (ChecEnabled())
{
await this.Dispatcher.InvokeAsync(() =>
{
StatusText.Text = String.Format("Status: Enabled. Watching for changes…");
});
}
else
{
await this.Dispatcher.InvokeAsync(() =>
{
StatusText.Text = String.Format("Status: Disabled");
});
}
}
catch (ObjectDisposedException)
{
//Window closed and disposed timer on different thread
}
//System Checks
await Task.Run(()=>UpdateSystemReadyStatus());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.