winform 跨线程

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

namespace WindowsFormsApplication12
{


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

        private void button1_Click(object sender, EventArgs e)
        {
            this.Text = Thread.CurrentThread.ManagedThreadId.ToString();

            Action<object> x1 = new Action<object>(x =>
            {





                for (int i = 0; i < (int)x; i++)
                {




                    Action<int> x2 = new Action<int>(
                        y =>
                        {
                            if (InvokeRequired)  // 跨线程访问
                            {
                                this.Invoke(new Action<object>(x10 => { button2.Text = x10.ToString(); this.Refresh(); Thread.Sleep(1000); }), i);
                            }
                            else
                            {
                                button2.Text = "ddd";
                            }
                        }

                        );




                    x2((int)i);
                    // Console.WriteLine(i.ToString());
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
                }

            });
            Thread t1 = new Thread(new ParameterizedThreadStart(x1));
            t1.IsBackground = true;
            t1.Start(10);
        }
    }
}

 

posted @ 2016-10-22 16:36  刀小爱  阅读(145)  评论(0)    收藏  举报