That's because of your ClickEvent
method. When you use Task.Run
to run some code, that code is run on a thread pool thread (logically, but you cannot rely on that behavior). Therefore you cannot access any UI elements inside this method. The only way to interact with the UI is on the thread that created it, hence the error. You cannot "asynchronously" update the UI. All UI calls must occur on the UI thread.
In your very specific case there is no benefit in using async at all. But a more realistic example does make sense.
private async void btnButton_Click(object sender, RoutedEventArgs e)
{
if (Click != null)
{
ProgressButton.Visibility = Visibility.Visible;
await DoWorkAsync();
ProgressButton.Visibility = Visibility.Hidden;
}
}
private Task DoWorkAsync ()
{
return Task.Run(() =>
{
//Do non UI work here
});
}