Hello all, I got some problem in handling thread so my form is not hang when performing a long time computing,
Here is my simple simulation of my program, first time my program start, it will make a form that contains a button that will perform a long time computing and a new window form that will monitoring the computing (it is needed to be real time), the problem is the long time computing must run on the main thread (it is a must),means it must run on the main window, so the problem is my monitoring window will be hang, and the graphic will not be real time, is there any way to trick this problem? if i make the monitoring window in different thread, is it safe?
Here is the sample code of my program

Form1.cs

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            compute c = new compute();
            c.computing();
        }
    }

Graphic.cs (monitoring purpose)

public graphic()
        {
            InitializeComponent();
        }
       
        public void updateLabel(int count)
        {
            label1.Text = "Value of i: " + count;
        }

Compute.cs (Computing purpose)

class compute
    {
        delegate void writeToForm(int i);
        graphic g = new graphic();

        public compute()
        {
            g.Show();
        }
        public void computing()
        {
           //THIS PART MUST RUN ON THE MAIN THREAD, DON'T MAKE IT ON THE OTHER THREAD
           //IT IS A MUST
            int count = 0;
            //THIS IS THE LONG TIME COMPUTING THING
            for (int i = 0; i < 100; i++)
            {
                count += i;
                updateLabel(count);
                Thread.Sleep(2000);
            }
        }

        private void updateLabel(int count)
        {
            if (g.InvokeRequired)
            {
                g.Invoke(new writeToForm(updateLabel), new object[] { count });
                return;
            }
            g.updateLabel(count);
        }
    }

My real program is not like this, but the program flow is the same, thanks for your help...

Recommended Answers

All 2 Replies

A must? Why? This is a nonsense.
All time consuming code must me on seperated thread, otherwise your UI will freeze (like it is now).

A must? Why? This is a nonsense.
All time consuming code must me on seperated thread, otherwise your UI will freeze (like it is now).

I'm using library that prevent his method to be ran from other thread, i don't know why, but i also must using that library, he said clearly on its documentation, never run the method except from the main thread, i can't do anything about it, sorry

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.