How to start a thread to keep GUI refreshed?

前端 未结 4 2044
北恋
北恋 2021-02-11 03:39

I have window with button which triggers lengthy processing. I put processing in a separate thread, but -- to my surprise -- it makes GUI frozen anyway. No control is refreshed,

4条回答
  •  太阳男子
    2021-02-11 03:53

    I faced the same situation, and solved it by two ways...

    1. Use the thread in other class and invoke it in ur main application by creating Thread, either in its constructor OR in any method.

    2. if u want do the it in same class, then create a Thread that call your function, and that function should invoke the Delegate.

    See the examples:

         public partial class Form1 : Form
        {
            private delegate void TickerDelegate();
            TickerDelegate tickerDelegate1;
    
            public Form1()
            {
                InitializeComponent();
            }
       //first solution
       // This button event call other class having Thread
    
           private void button1_Click(object sender, EventArgs e) 
            {
                f = new FormFileUpdate("Auto File Updater", this);
                f.Visible = true;
                this.Visible = false;         
            }
    
            // Second Solution
            private void BtnWatch_Click(object sender, EventArgs e)
            {
                tickerDelegate1 = new TickerDelegate(SetLeftTicker);
                Thread th = new Thread(new ThreadStart(DigitalTimer));
                th.IsBackground = true;
                th.Start();
             }
    
            private void SetLeftTicker()
            {
                label2.Text=DateTime.Now.ToLongTimeString();
            }
    
    
            public void DigitalTimer()
            {
                while (true)
                {
                    label2.BeginInvoke(tickerDelegate1, new object[] {});
                    Thread.Sleep(1000);
                }
            }
        }
    

提交回复
热议问题