I have a method that takes a few seconds to execute. I created also a big label that should appear right before the method is called and disappear when the method is finished to execute. However, my label doesn't appear even though the line that makes the label appear is placed before the method call. Why does my C# WPF code do that? How to fix this, so that my label appears before calling the method and disappears afterwards?
This is a sample of my code:
label.Visibility = Visible;
myMethod();
label.Visibility = Invisible;
I have a method that takes a few seconds to execute.
Then you shouldn't do that in the UI thread, basically. That blocks the UI thread, preventing the UI from updating.
You should perform long-running tasks in other threads, but make sure you only touch the UI itself from the UI thread.
With C# 5's async/await
functionality, this is relatively straightforward:
// This now needs to be in an async method
label.Visibility = Visible;
await Task.Run(() => myMethod());
label.Visibility = Invisible;
See more on this question at Stackoverflow