- using System;
- using System.Threading;
- namespace TaskDemo {
- public class MyTask {
- public Thread m_thread;
- string m_name;
- public MyTask(string name) {
- m_name = name;
- m_thread = new Thread(new ThreadStart(Worker)); // 线程创建,作为一个类的成员存在
- }
- private void Worker() {
- Console.WriteLine("Hello, ");
- Thread.Sleep(1500);
- Console.WriteLine(m_name);
- }
- }
- class TaskDemo1 {
- static void Main(string [] args) {
- MyTask task1 = new MyTask("Bill");
- MyTask task2 = new MyTask("Steve");
- task1.m_thread.Start(); //线程启动
- task2.m_thread.Start();
- }
- }
- }
-
-
- 关闭窗口结束线程
- private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
- {
- if(my_thread.ThreadState.ToString() =="Suspended") //先检查线程的状态
- {
- my_thread.Resume(); // 唤起
- my_thread.Abort(); //杀死线程
- my_thread.Join(); //这里是保证彻底的杀死线程吧
- }
- else
- {
- my_thread.Abort();
- my_thread.Join();
- }
- }
-
- 上面用到了一个叫做join和函数,它的作用是什么?
- t.Join();
- 可以这么理解,把线程t放到当前位置来执行,只有t结束以后才会执行t.Join()以后的代码
复制代码 |
|