2012-10-06 144 views
-3

我一直在研究一段代碼。我有一個問題:C#:線程和多線程的概念

什麼是「線程」和「多線程」在C#中的意思? 線程的作用是什麼?

+2

那是一個非常通用的和基本的問題該代碼。在谷歌搜索這個,我相信你會得到很多關於此的信息。 – Luftwaffe

+0

這個問題已經以許多不錯的方式回答了很多次,請儘量先試用Google。 –

+0

詳細瞭解它:http://www.albahari.com/threading/ – Tudor

回答

1

線程是一個進程的上下文中執行的指令序列。當程序使用多個執行線程時允許每個線程同時共享CPU,這取決於分配給這些線程的優先級。

你可以參考學習線程

using System; 
using System.Threading; 

public class Alpha 
{ 

    // This method that will be called when the thread is started 
    public void Beta() 
    { 
     while (true) 
     { 
     Console.WriteLine("Alpha.Beta is running in its own thread."); 
     } 
    } 
}; 

public class Simple 
{ 
    public static int Main() 
    { 
     Console.WriteLine("Thread Start/Stop/Join Sample"); 

     Alpha oAlpha = new Alpha(); 

     // Create the thread object, passing in the Alpha.Beta method 
     // via a ThreadStart delegate. This does not start the thread. 
     Thread oThread = new Thread(new ThreadStart(oAlpha.Beta)); 

     // Start the thread 
     oThread.Start(); 

     // Spin for a while waiting for the started thread to become 
     // alive: 
     while (!oThread.IsAlive); 

     // Put the Main thread to sleep for 1 millisecond to allow oThread 
     // to do some work: 
     Thread.Sleep(1); 

     // Request that oThread be stopped 
     oThread.Abort(); 

     // Wait until oThread finishes. Join also has overloads 
     // that take a millisecond interval or a TimeSpan object. 
     oThread.Join(); 

     Console.WriteLine(); 
     Console.WriteLine("Alpha.Beta has finished"); 

     try 
     { 
     Console.WriteLine("Try to restart the Alpha.Beta thread"); 
     oThread.Start(); 
     } 
     catch (ThreadStateException) 
     { 
     Console.Write("ThreadStateException trying to restart Alpha.Beta. "); 
     Console.WriteLine("Expected since aborted threads cannot be restarted."); 
     } 
     return 0; 
    } 
}