winfrom 多线程更新UI

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

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

        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(m));
            th.Start();
            th = new Thread(new ThreadStart(n));
            th.Start();
        }
        public void m()
        {
            for (int i = 0; i < int.MaxValue; i++)
            {
                lb1(i.ToString());
                Thread.Sleep(400);
            }
        }
        public void lb1(string lb1)
        {
            Thread thread = new Thread(new ThreadStart(delegate()
            {
                //for (int i = 0; i < 100; i++)
                //{
                //    Thread.Sleep(100);
                //    this.Invoke(new Action<int>(delegate(int a) { label1.Text= a + "/100"; }), i);
                //}
                this.Invoke(new Action<string>(delegate(string a) { label1.Text = a; }), lb1);
            }));
            thread.Start(); 
        }
        public void n()
        {
            for (int i = 0; i < int.MaxValue; i++)
            {
                lb2(i.ToString());
                Thread.Sleep(300);
            }
        }
        public void lb2(string lb2)
        {
            Thread thread = new Thread(new ThreadStart(delegate()
            {
                //for (int i = 0; i < 100; i++)
                //{
                //    Thread.Sleep(100);
                //    this.Invoke(new Action<int>(delegate(int a) { label1.Text= a + "/100"; }), i);
                //}
                this.Invoke(new Action<string>(delegate(string a) { label2.Text = a; }), lb2);
            }));
            thread.Start(); 
        }
    }
}

  

你可能感兴趣的:(winfrom 多线程更新UI)