I can update UI from background thread, why?

前端 未结 3 1821
暗喜
暗喜 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-14 00:05

    Everybody knows, that updating UI from background thread is not allowed

    Not everyone knows that. But it is true. Updating most UI elements from threads other than the UI thread is wrong.

    I don't understand how it is possible

    You pour a bunch of sand into your car's oil sump. You're not supposed to do that. So how is it possible that you just did so? Seems like a strange question to ask, doesn't it?

    Is the car required to stop you from doing so? No. Is it required that the engine stops running when you do so? No. Will the engine break eventually? Probably. But not necessarily.

    The engineers who designed your car assumed that you would not do something so wrong, so they did not build in any safety systems to prevent or detect this problem.

    what am I doing wrong?

    You're updating the UI from a background thread. Don't do that. But the runtime is not required to provide a safety system that prevents or detects your error. It is not required to produce an error when you do something that you shouldn't be doing in the first place. It can do so if it wants, or not, at its discretion.

    Or, think about it this way. Suppose you were implementing the runtime so that it had the property you thought it had: that the runtime will always detect bad cross-thread calls and produce an error when they happen. That's a feature. Someone has to design, write, test, and maintain that code. What does the code look like, and what are all the costs associated with it?

提交回复
热议问题