Thursday, October 27, 2016

Open form in the UI thread from another thread

Problem
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();
            globalForm.Show();
            globalForm.Hide();

            Task t = new Task(Run);
            t.Start();

        }

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

                //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)
                {
                   test.Show();
                    test.Activate();
                 };
            };
            globalForm.Invoke(m);
        }

No comments:

Post a Comment

There was an error in this gadget