Run code on UI thread without control object present

前端 未结 5 1773
予麋鹿
予麋鹿 2020-12-08 16:57

I currently trying to write a component where some parts of it should run on the UI thread (explanation would be to long). So the easiest way would be to pass a control to i

5条回答
  •  自闭症患者
    2020-12-08 17:32

    First, in your form constructor, keep a class-scoped reference to the SynchronizationContext.Current object (which is in fact a WindowsFormsSynchronizationContext).

    public partial class MyForm : Form {
        private SynchronizationContext syncContext;
        public MyForm() {
            this.syncContext = SynchronizationContext.Current;
        }
    }
    

    Then, anywhere within your class, use this context to send messages to the UI:

    public partial class MyForm : Form {
        public void DoStuff() {
            ThreadPool.QueueUserWorkItem(_ => {
                // worker thread starts
                // invoke UI from here
                this.syncContext.Send(() =>
                    this.myButton.Text = "Updated from worker thread");
                // continue background work
                this.syncContext.Send(() => {
                    this.myText1.Text = "Updated from worker thread";
                    this.myText2.Text = "Updated from worker thread";
                });
                // continue background work
            });
        }
    }
    

    You will need the following extension methods to work with lambda expressions: http://codepaste.net/zje4k6

提交回复
热议问题