C#多线程使用示例


分享一下C#多线程的使用示例

贴上代码:

namespace ThreadingTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public delegate int Mydelegate(int arg);
        string str1 = "";
        string str2 = "";
        string str3 = "";
        string str4 = "";
        string str5 = "";
        Thread t1;
        Thread t2;
        Thread t3;
        Thread t4;
        Thread t5;
        private void Do()
        {
            t1 = new Thread(Hellow1);
            t2 = new Thread(new ThreadStart(Hellow2));
            t3 = new Thread(new ParameterizedThreadStart(Hellow3));
            t4 = new Thread(Hellow4);
            t5 = new Thread(Run);
            t1.Start();
            t2.Start();
            t3.Start(3333333);
            t4.Start(444444444);
            t5.Start();
            timer1.Start();
        }
        private void Run()//有返回值的委托
        {
            Mydelegate dele = new Mydelegate(Hellow5);
            str5 = dele.EndInvoke(dele.BeginInvoke(66666666, null, null)).ToString();//会挂起线程,直到有返回值为止
        }
        private void Hellow1()
        {
            str1 = "11111111";
        }
        private void Hellow2()
        {
            str2 = "222222222";
        }
        private void Hellow3(object str)
        {
            str3 = Convert.ToString(str);
        }
        private void Hellow4(object str)
        {
            str4 = Convert.ToString(str);
        }
        private int Hellow5(int value)
        {
            Thread.Sleep(5000);
            return value;
        }
        private void Button1_Click(object sender, EventArgs e)
        {
            Do();
        }
        private void Timer1_Tick(object sender, EventArgs e)
        {
            textBox1.Text = str1;
            textBox2.Text = str2;
            textBox3.Text = str3;
            textBox4.Text = str4;
            textBox5.Text = str5.ToString();
        }
    }
}