Why can't UI components be accessed from a backgroundworker?

前端 未结 3 749
星月不相逢
星月不相逢 2021-01-21 18:20

Threads all share resources. That\'s the whole problem around multi-threaded operations.

MSDN says:

You must be careful not to manipulate any user

3条回答
  •  情书的邮戳
    2021-01-21 19:14

    It can be done with something as simple as having each control store the current thread (or maybe just its ID) in a private field in the constructor and then checking if the current thread is still that one before every method. Something like this:

    class ThreadAffineObject
    {
        private readonly Thread originalThread;
        public ThreadAffineObject()
        {
            this.originalThread = Thread.CurrentThread;
        }
    
        private void PreventCrossThreadOperation()
        {
            if(Thread.CurrentThread != originalThread)
                throw new CrossThreadOperationException();
        }
    
        public void DoStuff()
        {
            PreventCrossThreadOperation();
            // Actually do stuff
        }
    
        private int someField;
        public int SomeProperty
        {
            get { return someField; } // here reading is allowed from other threads
            set
            {
                PreventCrossThreadOperation(); // but writing isn't
                someField = value;
            }
        }
    }
    

提交回复
热议问题