Thursday, October 27, 2016

Open form in the UI thread from another thread

I have a thread that wakes up and processes stuff based on a schedule and it needs to show progress in a window. This is so that if any user happens to be using the system when this pops up, they can cancel it / see what's going on.

Solution - create a dummy form to Invoke()
        public static Form globalForm;
        private void btnStart_Click(object sender, EventArgs e)
            globalForm = new Form();

            Task t = new Task(Run);


        Test test; //this is the form i want to show when this job is running
        public void Run()
            test = new Test();
            while (true)

                //do stuff

                //update status on the window

        private void ShowTestForm()
             /* Note: I prefer this wrapped version over calling globalForm.Invoke(...) from the Run() method. I believe this is cleaner code.  */

            MethodInvoker m = () =>
                if (!test.Visible)

No comments:

Post a Comment