I can update the interface from the background thread, why?

Everyone knows that updating the user interface from a background thread is not allowed (or not?)

I did a little experiment. Here is the code snippet:

var thread = new Thread(() => progressBar1.Increment(50));
            thread.IsBackground = true;
            thread.Start();
            thread.Join();

I put this code in some button click handler. And you know what? My progress bar is increasing ... From the background thread. And now I'm embarrassed. I do not understand how this is possible, and what I am doing wrong.

+4
source share
3 answers

I can update the interface from the background thread, why?

, , . , Control.CheckForIllegalCrossThreadCalls Property.

private static bool checkForIllegalCrossThreadCalls = Debugger.IsAttached;
public static bool CheckForIllegalCrossThreadCalls {
    get { return checkForIllegalCrossThreadCalls; }
    set { checkForIllegalCrossThreadCalls = value; }
}

, .

Main ( Application.Run)

Control.CheckForIllegalCrossThreadCalls = true;

.

+7

,

. . , , .

,

. . , ? , , , ?

, ? . , , ? . , ? . .

, , , - , , .

?

. . , . , , . , , , .

, . , , , , , : . . - , , . ?

+4

Like varocarbas, any component that you put in your constructor throws a Cross thread exception.

to access the stream you need to use invke, beginInvoke.

try to run

BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s1,e1) => 
{
    textBoxt1.Text = "foo";  // Exception here
} 
bw.RunWorkerCompleted += (1s, e1) =>
{
    textBoxt1.Text = "foo";  // No exception here off UI thread
}
bw.RunWorkerAsync();

replace instead

bw.DoWork += (s1,e1) => 
{
    this.Invoke((MethodInvoker) delegate 
   {
        textBoxt1.Text = message;
   });  // No Exception now
} 
-1
source

Source: https://habr.com/ru/post/1620911/


All Articles