日期:2014-05-18  浏览次数:20812 次

C#Thread类—多线程

创建包含线程的 Visual C# 应用程序

  1. 启动 Microsoft Visual Studio .NET、Microsoft Visual Studio 2010 或 Microsoft Visual 2008。
  2. 新建一个名为 ThreadWinApp 的 Visual C# Windows 应用程序项目。
  3. 向窗体中添加一个“按钮”控件。默认情况下,此按钮名为“Button1”。
  4. 向窗体中添加一个“ProgressBar”组件。默认情况下,此进度栏名为“ProgressBar1”。
  5. 右键单击该窗体,然后单击“查看代码”。
  6. 将以下语句添加到该文件的开头:
    using System.Threading;
  7. 为“Button1”添加以下“Click”事件处理程序:
    private void button1_Click(object sender, System.EventArgs e)
    {
    	MessageBox.Show("This is the main thread");
    }
  8. 将以下变量添加到“Form1”类中:
    private Thread trd;
    
  9. 将以下方法添加到“Form1”类中:
    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 毫秒后再继续。
  10. 为“Form1”添加以下“Load”事件处理程序。此段代码将新建一个线程,使该线程成为后台线程,然后启动该线程。