线程

1.当使用线程的时候,一般设置线程IsBackground=true;表示后台线程,主进程在被结束的时候也会自动结束所有后台线程。
当false;表示前台进程,在没有结束该线程之前是不能结束主进程的。

2.当一个线程为后台线程的时候,它是不能直接操作前台控件的,因为前台WinForm控件都是COM控件,只能被主进程调用。
这时候就要用Invoke的委托来调用。

View Code
 1 public Form1()
 2  {
 3      InitializeComponent();
 4      Close();
 5      bTime = e.BeginTime;
 6      eTime = e.EndTime;
 7      Thread thread = new Thread(new ThreadStart(RunLoad));
 8      thread.IsBackground = true;
 9      thread.Start();
10  }
11 
12  private void RunLoad()
13  {
14      Invoke
15      (
16      new System.Windows.Forms.MethodInvoker
17      (
18          delegate()
19          {
20          Init(bTime, eTime);
21          }
22      )
23  }

3.线程停止

View Code
 1 CancellationTokenSource cts = new CancellationTokenSource();            
 2 Thread t = new Thread(() => {
 3 while (true)
 4 {   
 5   if (cts.Token.IsCancellationRequested)
 6 {                            
 7 Console.WriteLine("线程被终止!");                     
 8 break;                        
 9 }                        
10 Console.WriteLine(DateTime.Now.ToString());                        
11 Thread.Sleep(1000);                    
12 }                
13 });            
14 t.Start();            
15 Console.ReadLine();            
16 cts.Cancel();
posted @ 2012-05-07 17:35  一篮饭特稀  阅读(160)  评论(0编辑  收藏  举报