Everybody knows, that updating UI from background thread is not allowed (or not?)
I did a little experiment. Here is a piece of code:
var thread = new Thread(() => progressBar1.Increment(50));
thread.IsBackground = true;
thread.Start();
thread.Join();
I put this code in some button click handler. And know what? My progressbar is incrementing...From background thread. And now I am confused. I don't understand how it is possible and what am I doing wrong
I can update UI from background thread, why?
Most probably you can do that when running outside the debugger. This is because that protection is controlled by the Control.CheckForIllegalCrossThreadCalls Property. Let take a look at reference source
private static bool checkForIllegalCrossThreadCalls = Debugger.IsAttached;
public static bool CheckForIllegalCrossThreadCalls {
get { return checkForIllegalCrossThreadCalls; }
set { checkForIllegalCrossThreadCalls = value; }
}
As you may see, this protection is enabled by default only when you are debugging.
If you add the following line in your Main
method (before Application.Run
)
Control.CheckForIllegalCrossThreadCalls = true;
your code will not work anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With