Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can update UI from background thread, why?

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

like image 511
Toddams Avatar asked Dec 19 '22 21:12

Toddams


1 Answers

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.

like image 51
Ivan Stoev Avatar answered Jan 06 '23 23:01

Ivan Stoev