I can update UI from background thread, why?

前端 未结 3 1851
暗喜
暗喜 2021-01-13 23:21

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 = ne         


        
3条回答
  •  太阳男子
    2021-01-13 23:56

    Like varocarbas says any component you put into your designer will throw Cross thread exception.

    to access between thread 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();
    

    instead replace

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

提交回复
热议问题