c# Thread類


現在C#已經建議擯棄使用 Suspend, Resume 暫停/恢復線程, 也盡量少用 Abort方法中斷一個線程.

建議使用線程的同步手段有:  Mutex、ManualResetEvent、AutoResetEvent, Monitor.

下面再對此進行詳細描述.

Thread類的構造函數有2類:

 一種是不帶參數(ThreadStart 委托) --

public Thread(ThreadStart start);

另一種是帶參數(ParameterizedThreadStart 委托) --

public Thread(ParameterizedThreadStart start);

ParameterizedThreadStart 委托簽名:

public delegate void ParameterizedThreadStart(Object obj);

示例:

1. 不帶參數:

// 定義線程方法:
private static void ThreadMain()
{
       Console.WriteLine("This is other thread main method.");
}
// 調用:
Thread mythread = new Thread(ThreadMain);
mythread.Start();

2. 帶參數:

// 定義線程方法:
private static void MainThreadWithParameters(object o)
{
      Data d = (Data)o;  //類型轉換
      Console.WriteLine("Running in a thread, received {0}", d.Message);
}

public struct Data
{
      public string Message;
}

// 調用:
var data = new Data { Message = "Info" };
Thread t2 = new Thread(MainThreadWithParameters);
t2.Start(data);  // 傳入參數

3. 通過定義類傳遞參數:

// 定義存放數據和線程方法的類:
public class MyThread
{
   private string message;
   public MyThread(string data)
   {
      this.message = data;
   }
   public void ThreadMethod()
   {
      Console.WriteLine("Running in a thread, data: {0}", this.message);  
   }
}
// 調用
var obj = new MyThread("info");
Thread myThread = new Thread(obj.ThreadMethod); //ThreadStart 委托
mythread.Start(); 

 

C#中,Thread類有一個IsBackground 的屬性.MSDN上對它的解釋是:獲取或設置一個值,該值指示某個線程是否為后台線程。

.Net中的線程,可以分為后台線程和前台線程。后台線程與前台線程並沒有本質的區別,它們之間唯一的區別就是:后台線程不會防止應用程序的進程被終止掉。就是當前台線程都結束了的時候,整個程序也就結束了,即使還有后台線程正在運行,此時,所有剩余的后台線程都會被停止且不會完成.但是,只要還有一個前台線程沒有結束,那么它將阻止程序結束.應用程序進程的存亡由前台線程決定而於后台線程無關.這就是它們的區別.改變線程從前台到后台不會以任何方式改變它在CPU協調程序中的優先級和狀態。因為前台后線程與程序進程的優先級無關.下面的代碼示例對比了前台線程與后台線程的行為。創建一個前台線程和一個后台線程。前台線程使進程保持運行,直到它完成它的 while 循環。前台線程完成后,進程在后台線程完成它的 while 循環之前終止。

using System;
using System.Threading;

class Test
{
    static void Main()
    {
        BackgroundTest shortTest = new BackgroundTest(10);
        Thread foregroundThread = 
            new Thread(new ThreadStart(shortTest.RunLoop));
        foregroundThread.Name = "ForegroundThread";

        BackgroundTest longTest = new BackgroundTest(50);
        Thread backgroundThread = 
            new Thread(new ThreadStart(longTest.RunLoop));
        backgroundThread.Name = "BackgroundThread";
        backgroundThread.IsBackground = true;

        foregroundThread.Start();
        backgroundThread.Start();
    }
}

class BackgroundTest
{
    int maxIterations;

    public BackgroundTest(int maxIterations)
    {
        this.maxIterations = maxIterations;
    }

    public void RunLoop()
    {
        String threadName = Thread.CurrentThread.Name;
        
        for(int i = 0; i < maxIterations; i++)
        {
            Console.WriteLine("{0} count: {1}", 
                threadName, i.ToString());
            Thread.Sleep(250);
        }
        Console.WriteLine("{0} finished counting.", threadName);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM