转:
使用线程,需要using System.Threading
1. 线程执行的程序代码由ThreadStart委托或ParameterizedThreadStart委托指定。
Thread MyThread = new Thread(new ThreadStart(MyMethod));
-
启动主线程
MyThread.Start(); -
通过主线程阻止新开线程
MyThread.Abort();
4.等待新开的线程结束
MyThread.Join();
1.2 线程实例
C# 创建一个新线程
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
{
class Program
{
static void Main()
{
//给线程提供调用方法 MyMethod
Thread MyThread = new Thread(new ThreadStart(MyMethod));
//开始 MyThread 线程
MyThread.Start();
//主线程休息5毫秒
Thread.Sleep(5);
//结束 MyThread 线程
MyThread.Abort();
//主线程等待MyThread 中止
MyThread.Join();
Console.WriteLine("MyThread. has finished");
Console.ReadLine();
}
public void MyMethod()
{
while (true)
{
Console.WriteLine("My Method is running .");
}
}
}
}