C#Thread类—多线程
using System.Threading;
private void button1_Click(object sender, System.EventArgs e){MessageBox.Show("This is the main thread");}
private Thread trd;
private void ThreadTask(){int stp;int newval;Random rnd=new Random();while(true){stp=this.progressBar1.Step*rnd.Next(-1,2);newval = this.progressBar1.Value + stp;if (newval > this.progressBar1.Maximum)newval = this.progressBar1.Maximum;else if (newval < this.progressBar1.Minimum)newval = this.progressBar1.Minimum;this.progressBar1.Value = newval;Thread.Sleep(100);}}注意:这是线程的底层代码。此段代码是一个无限循环,它随机增加或减小“ProgressBar1”中的值,然后等待 100 毫秒后再继续。
private void Form1_Load(object sender, System.EventArgs e){Thread trd = new Thread(new ThreadStart(this.ThreadTask));trd.IsBackground = true;trd.Start();}