C#中编写多线程应用程序

以前在使用VB来实现多线程的时候,发现有一定的难度。虽然也有这样那样的方法,但都不尽人意,但在C#中,要编写多线程应用程序却相当的简单。这篇文章将作简要的介绍,以起到抛砖引玉的作用!
    .NET将关于多线程的功能定义在System.Threading名字空间中。因此,要使用多线程,必须先声明引用此名字空间(using System.Threading;)。
       即使你没有编写多线程应用程序的经验,也可能听说过“启动线程”“杀死线程”这些词,其实除了这两个外,涉及多线程方面的还有诸如“暂停线程”“优先级”“挂起线程”“恢复线程”等等。下面将一个一个的解释。
    a.启动线程
    顾名思义,“启动线程”就是新建并启动一个线程的意思,如下代码可实现:
    Thread thread1 = new Thread(new ThreadStart( Count));
    其中的 Count 是将要被新线程执行的函数。
    b.杀死线程
    “杀死线程”就是将一线程斩草除根,为了不白费力气,在杀死一个线程前最好先判断它是否还活着(通过 IsAlive 属性),然后就可以调用 Abort 方法来杀死此线程。
    c.暂停线程
    它的意思就是让一个正在运行的线程休眠一段时间。如 thread.Sleep(1000); 就是让线程休眠1秒钟。
    d.优先级
    这个用不着解释了。Thread类中有一个ThreadPriority属性,它用来设置优先级,但不能保证操作系统会接受该优先级。一个线程的优先级可分为5种:Normal, AboveNormal, BelowNormal, Highest, Lowest。具体实现例子如下:
    thread.Priority = ThreadPriority.Highest;
    e.挂起线程
    Thread类的Suspend方法用来挂起线程,知道调用Resume,此线程才可以继续执行。如果线程已经挂起,那就不会起作用。
    if (thread.ThreadState = ThreadState.Running)
    {
         thread.Suspend();
    }
    f.恢复线程
    用来恢复已经挂起的线程,以让它继续执行,如果线程没挂起,也不会起作用。
    if (thread.ThreadState = ThreadState.Suspended)
    {
         thread.Resume();
    }
    下面将列出一个例子,以说明简单的线程处理功能。此例子来自于帮助文档。
    using System;
    using System.Threading;

    // Simple threading scenario:  Start a static method running
    // on a second thread.
    public class ThreadExample {
        // The ThreadProc method is called when the thread starts.
        // It loops ten times, writing to the console and yielding
        // the rest of its time slice each time, and then ends.
        public static void ThreadProc() {
            for (int i = 0; i < 10; i++) {
                Console.WriteLine("ThreadProc: {0}", i);
                // Yield the rest of the time slice.
                Thread.Sleep(0);
            }
        }
   
        public static void Main() {
            Console.WriteLine("Main thread: Start a second thread.");
            // The constructor for the Thread class requires a ThreadStart
            // delegate that represents the method to be executed on the
            // thread.  C# simplifies the creation of this delegate.
            Thread t = new Thread(new ThreadStart(ThreadProc));
            // Start ThreadProc.  On a uniprocessor, the thread does not get
            // any processor time until the main thread yields.  Uncomment
            // the Thread.Sleep that follows t.Start() to see the difference.
            t.Start();
            //Thread.Sleep(0);
   
            for (int i = 0; i < 4; i++) {
                Console.WriteLine("Main thread: Do some work.");
                Thread.Sleep(0);
            }
   
            Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
            t.Join();
            Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
            Console.ReadLine();
        }
    }
   
       此代码产生的输出类似如下内容:

    Main thread: Start a second thread.
    Main thread: Do some work.
    ThreadProc: 0
    Main thread: Do some work.
    ThreadProc: 1
    Main thread: Do some work.
    ThreadProc: 2
    Main thread: Do some work.
    ThreadProc: 3
    Main thread: Call Join(), to wait until ThreadProc ends.
    ThreadProc: 4
    ThreadProc: 5
    ThreadProc: 6
    ThreadProc: 7
    ThreadProc: 8
    ThreadProc: 9
    Main thread: ThreadProc.Join has returned.  Press Enter to end program

 

 

c#中使用多线程(图)     选择自 iuhxq 的 Blog
 

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

using System.Threading;

namespace student
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.Button button2;
  private System.Windows.Forms.Button button3;

  ArrayList threads = new ArrayList();

  private System.Windows.Forms.ListView listView1;
  private System.Windows.Forms.ColumnHeader columnHeader1;
  private System.Windows.Forms.ColumnHeader columnHeader2;
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.button1 = new System.Windows.Forms.Button();
   this.button2 = new System.Windows.Forms.Button();
   this.button3 = new System.Windows.Forms.Button();
   this.listView1 = new System.Windows.Forms.ListView();
   this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
   this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
   this.SuspendLayout();
   //
   // button1
   //
   this.button1.Location = new System.Drawing.Point(24, 216);
   this.button1.Name = "button1";
   this.button1.TabIndex = 1;
   this.button1.Text = "Add";
   this.button1.Click += new System.EventHandler(this.button1_Click);
   //
   // button2
   //
   this.button2.Location = new System.Drawing.Point(104, 216);
   this.button2.Name = "button2";
   this.button2.TabIndex = 2;
   this.button2.Text = "Del";
   this.button2.Click += new System.EventHandler(this.button2_Click);
   //
   // button3
   //
   this.button3.Location = new System.Drawing.Point(184, 216);
   this.button3.Name = "button3";
   this.button3.TabIndex = 3;
   this.button3.Text = "DelAll";
   this.button3.Click += new System.EventHandler(this.button3_Click);
   //
   // listView1
   //
   this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
                      this.columnHeader1,
                      this.columnHeader2});
   this.listView1.FullRowSelect = true;
   this.listView1.GridLines = true;
   this.listView1.Location = new System.Drawing.Point(0, 0);
   this.listView1.Name = "listView1";
   this.listView1.Size = new System.Drawing.Size(288, 208);
   this.listView1.TabIndex = 5;
   this.listView1.View = System.Windows.Forms.View.Details;
   //
   // columnHeader1
   //
   this.columnHeader1.Text = "线程编号";
   this.columnHeader1.Width = 81;
   //
   // columnHeader2
   //
   this.columnHeader2.Text = "value";
   this.columnHeader2.Width = 180;
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(292, 266);
   this.Controls.Add(this.listView1);
   this.Controls.Add(this.button3);
   this.Controls.Add(this.button2);
   this.Controls.Add(this.button1);
   this.Name = "Form1";
   this.Text = "Form1";
   this.Load += new System.EventHandler(this.Form1_Load);
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void Form1_Load(object sender, System.EventArgs e)
  {
  
  }

  private void button1_Click(object sender, System.EventArgs e)
  {
   Add();
  }

  private void button2_Click(object sender, System.EventArgs e)
  {
   Del();
  }

  private void button3_Click(object sender, System.EventArgs e)
  {

   while(threads.Count>0)
   {
    Thread t1 = (Thread)threads[0];
    if(t1.IsAlive)
    {
     t1.Abort();
    }
    threads.RemoveAt(0);
    lock(listView1)
    {
     listView1.Items.RemoveAt(0);
    }
   }
  }

  private void Add()
  {
   int count = threads.Count;
   if(count<10)
   {
    Thread t = new Thread(new ThreadStart(Process));
    t.Start();
    threads.Add(t);
    lock(listView1)
    {
     listView1.Items.Insert(count, new ListViewItem(new string[]{count.ToString(),"0"}));
    }
   }
  }

  private void Del()
  {
   int count = threads.Count;
   if(count>0)
   {
    Thread t1 = (Thread)threads[count-1];
    if(t1.IsAlive)
    {
     t1.Abort();
    }
    threads.RemoveAt(count-1);
    lock(listView1)
    {
     listView1.Items.RemoveAt(count-1);
    }
   }
  }


  private void Process()
  {
   int i = 1;
   while(true)
   {
    i++;
    int j = threads.IndexOf(Thread.CurrentThread);
    lock(listView1)
    {
     listView1.Items[j].SubItems[1].Text = i.ToString();
    }
    Thread.Sleep(0);
   }
  }
 }
}

  }
 }
}
C中编写多线程应用程序 - 非哦我 - happy
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值