多线程是计算机同时执行多个任务,大大提高效率,尤其对于一些方法需要同时执行的情况
Thread
命名空间System.Threading
Thread创建线程
ThreadStart 可有可无
static void Main(string[] args)
{
ThreadStart start = new ThreadStart(ChildTread);// ThreadStart对方法进行创建线程
Thread thread = new Thread(start);//Thread 对线程进行操作
thread.Start();//开始线程
Console.WriteLine("Main结束");
}
private static void ChildTread()
{
Console.WriteLine("ChildThread结束");
}
线程也可以使用lambda表达式
Thread thread = new Thread(()=>Console.WriteLine(""));
static void Main(string[] args)
{
var thread = new Thread(() => { Thread.Sleep(100); Console.WriteLine("1234"); }) { IsBackground=false};
thread.Start();
Console.WriteLine("Main结束");
}
Sleep(),Abort()
Thread类提供了其他方法Sleep(),Abort()
Thread.Sleep(i);//对当前的线程暂停i毫秒,i为整型
Thread thread = new Thread(start);//Thread 对线程进行操作
thread.Abort();//销毁线程
下面是其中一个测试,及其结果
static void Main(string[] args)
{
ThreadStart start = new ThreadStart(ChildTread);// ThreadStart对方法进行创建线程
Thread thread = new Thread(start);//Thread 对线程进行操作
thread.Abort();
try
{
thread.Start();//在销毁线程后进行开始
}
catch (Exception e)
{
Console.Write(e);//抛出异常结果
}
Console.WriteLine("Main结束");
}
private static void ChildTread()
{
Console.WriteLine("ChildThread结束");
}
System.Threading.ThreadStartException: 线程未能启动。 ---> System.Threading.ThreadAbortException: 正在中止线程。
--- 内部异常堆栈跟踪的结尾 ---
在 System.Threading.Thread.StartInternal(IPrincipal principal, StackCrawlMark& stackMark)
在 System.Threading.Thread.Start(StackCrawlMark& stackMark)
在 System.Threading.Thread.Start()
在 _2_多线程.Program.Main(String[] args) 位置 E:\C#数据结构\1\2_多线程\Program.cs:行号 20Main结束
请按任意键继续. . .
异步委托
这是一个委托
delegate void dele();
public static void Test()
{
Console.WriteLine("Start!");
Thread.Sleep(100);
Console.WriteLine("Continue!");
Thread.Sleep(100);
Console.WriteLine("END!");
}
static void Main(string[] args)
{
dele dele = Test;
dele();
Console.WriteLine("Main END");
}
由委托开启线程
delegate void dele();
public static void Test()
{
Console.WriteLine("Start!");
Thread.Sleep(100);
Console.WriteLine("Continue!");
Thread.Sleep(100);
Console.WriteLine("END!");
}
static void Main(string[] args)
{
dele dele = Test;
dele.BeginInvoke(null, null);//开启一个线程,dele();
Console.WriteLine("Main END");
}
但是可以看到委托的方法未执行完,但当主函数结束,程序便结束了
若将其用thread类实现,可以很明显看到,主线程和子线程都执行完了,他们是同步调用的
public static void Test()
{
Console.WriteLine("Start!");
Thread.Sleep(100);
Console.WriteLine("Continue!");
Thread.Sleep(100);
Console.WriteLine("END!");
}
static void Main(string[] args)
{
Thread thread = new Thread(Test);//建立操作线程的方法
thread.Start();
Console.WriteLine("Main END");
}
thread和异步委托相当于前台线程和后台线程;
前台线程在main函数执行完成后依然会继续执行,程序不会结束;
后台线程在main函数执行完后会全部关闭
不过后台线程一般是在建立线程后面加上{ IsBackground=true},当为true时便是后台线程
public static void Test()
{
Console.WriteLine("Start!");
Thread.Sleep(100);
Console.WriteLine("Continue!");
Thread.Sleep(100);
Console.WriteLine("END!");
}
static void Main(string[] args)
{
Thread thread = new Thread(Test) { IsBackground = true };//后台委托
thread.Start();
Console.WriteLine("Main END");
}
执行结果:可以看到与异步委托执行结果相同