首頁  >  文章  >  後端開發  >  C# 執行緒

C# 執行緒

王林
王林原創
2024-09-03 15:25:25288瀏覽

以下文章提供了 C# 主題的概述。程式的執行路徑被定義為線程,並且每個線程都定義了唯一的控制流。當應用程式包含複雜且耗時的操作時,必須設定不同的執行路徑或線程,其中每個線程負責特定的作業。這些輕量級的線程進程和實現並發編程的現代作業系統是使用線程的範例之一,透過使用線程,可以節省中央處理單元的周期浪費並提高應用程式的效率。

文法:

public sealed class Thread: System.Runtime.ConstrainedExecution.CriticalFinalizerObject

C# 執行緒類別的工作

當執行緒的生命週期開始時,System.Threading.Thread類別的物件被建立的時間。當執行緒終止或執行緒執行完成時,執行緒被建立並結束。

執行緒的生命週期有幾種狀態。

1。未啟動狀態:這種狀態是指未呼叫start方法但建立了執行緒實例的情況。

2。就緒狀態:該狀態是執行緒已準備好運作並等待中央處理器週期的情況。

3。不可運作狀態:此狀態是執行緒在下列情況下無法執行的情況:

  • 已呼叫 Sleep 方法。
  • 已呼叫 Wait 方法。
  • 輸入/輸出操作出現阻塞。

4。死亡狀態:該狀態是執行緒執行完成,或執行緒執行中止的情況。

  • 為了在 C# 中使用線程,我們必須使用 System.Threading.Thread 類別。
  • 在使用多執行緒應用程式時,可以使用 C# 中的 System.Threading.Thread 類別建立和存取單一執行緒。
  • 整個行程中最先執行的執行緒稱為主執行緒。
  • 主執行緒在C#程式開始執行時自動建立。
  • 使用 Thread 類別建立的執行緒稱為主執行緒的子執行緒。
  • Thread 類別的 CurrentThread 屬性用於存取執行緒。

下面的程式示範了主執行緒的執行:

代碼:

using System;
using System.Threading;
//a namespace called multithreading is created
namespace Multithreading
{
//a class called mainthread is created under multithreading namespace
class MainThread
{
//main method is called
static void Main(string[] args)
{
//an instance of the thread class is created
Thread thr = Thread.CurrentThread;
//Name method of thread class is accessed using the instance of the thread class
thr.Name = "Thread Class";
//the content is displayed as the output
Console.WriteLine("Welcome to {0}", thr.Name);
Console.ReadKey();
}
}
}

輸出:

C# 執行緒

在上面的程式中,建立了一個名為多執行緒的命名空間。然後在多執行緒命名空間下建立一個名為mainthread的類別。然後呼叫一個main方法。然後創建線程類別的實例。然後使用線程類別的實例存取線程類別的Name方法。最後輸出顯示在螢幕上。

Thread 類別的方法

以下是幾個線程類別的方法:

1.中止()

每當在執行緒上呼叫 Abort() 方法時,都會引發 ThreadAbortException 並開始終止執行緒的過程。呼叫該方法會導致執行緒終止。

範例: 

代碼:

using System;
using System.Threading;
class ExThread
{
public void thr()
{
for (int y = 0; y < 3; y++)
{
Console.WriteLine(y);
}
}
}
class Example
{
public static void Main()
{
ExThread ob = new ExThread();
Thread th = new Thread(new ThreadStart(ob.thr));
th.Start();
Console.WriteLine("Aborting the thread");
th.Abort();
}
}

輸出:

C# 執行緒

2.中斷()

每當呼叫 Interrupt() 方法時,處於 WaitSleepJoin 執行緒狀態的執行緒就會被中斷。

3.加入()

每當呼叫 Join() 方法時,呼叫執行緒都會被阻塞,直到執行緒終止,並且標準 COM 和 SendMessage 泵送將在執行緒阻塞的同時繼續執行。

實作 Interrupt() 和 Join() 的範例:

代碼:

using System;
using System.Threading;
class Thr
{
Thread th;
public Thr(String name1)
{
th = new Thread(this.Runaway);
th.Name = name1;
th.Start();
}
public void Runaway()
{
Thread th1 = Thread.CurrentThread;
try
{
Console.WriteLine(" Execution of " + th1.Name + " has begun");
for(int y=0; y<3; y++)
{
Console.WriteLine(" Printing of " + th1.Name + " has begun" + y);
Thread.Sleep(200);
}
Console.WriteLine(" Execution of " + th1.Name + " is finished");
}
catch(ThreadInterruptedException e)
{
Console.WriteLine("Thread Interruption" + e);
}
}
public static void Main(String[] ar)
{
Thr ob = new Thr("Thread demo");
ob.th.Interrupt();
ob.th.Join();
}
}

輸出:

C# 執行緒

4. ResetAbort()

每當呼叫 ResetAbort() 方法時,目前執行緒的終止請求就會被取消。

範例:

代碼:

using System;
using System.Threading;
using System.Security.Permissions;
class Thread1
{
public void Jobthread()
{
try
{
for (int r = 0; r < 3; r++)
{
Console.WriteLine(" Working of thread has begun ");
Thread.Sleep(10);
}
}
catch (ThreadAbortException e)
{
Console.WriteLine("ThreadAbortException is caught and must be reset");
Console.WriteLine("The message looks like this: {0}", e.Message);
Thread.ResetAbort();
}
Console.WriteLine("Thread is working fine");
Thread.Sleep(200);
Console.WriteLine("Thread is done");
}
}
class Driver
{
public static void Main()
{
Thread1 obj = new Thread1();
Thread Th = new Thread(obj.Jobthread);
Th.Start();
Thread.Sleep(100);
Console.WriteLine("thread abort");
Th.Abort();
Th.Join();
Console.WriteLine("end of main thread");
}
}

輸出:

C# 執行緒

5.開始()

每當呼叫 Start() 方法時,都會啟動一個執行緒。

範例:

代碼:

using System;
using System.Threading;
class Test
{
static void Main()
{
Thread td = new Thread (new ThreadStart (Got));
td.Start();
}
static void Got()
{
Console.WriteLine ("this is thread Start() method");
}
}

輸出:

C# 執行緒

6.睡眠(int毫秒超時)

每當呼叫 Sleep(int millisecondsTimeout) 方法時,執行緒就會暫停指定的時間。

範例:

代碼:

using System;
using System.Threading;
namespace Examplethr
{
class MyThread
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "This is the First Thread";
Console.WriteLine("The Name of the thread is : {0}", th.Name);
Console.WriteLine("The priority of the thread is : {0}", th.Priority);
Console.WriteLine("Pausing the child thread");
// using Sleep() method
Thread.Sleep(100);
Console.WriteLine("Resuming the child thread");
Console.ReadKey();
}
}
}

輸出:

C# 執行緒

7. Suspend()

Whenever Suspend() method is called, the current thread is suspended if it is not suspended.

8. Resume()

Whenever Resume() method is called, the suspended thread is resumed.

9. Yield()

Whenever Yield() method is called, the calling thread must result in execution to the other thread which is ready to start running on the current processor. The thread to yield to is selected by the operating system.

Example to implement Suspend() Resume() and Yield()

Code:

using System;
using System.Runtime.CompilerServices;
using System.Threading;
class Program
{
public static void Main ()
{
bool finish = false;
Thread th = new Thread (() => {
while (!finish) {}
});
Thread th1 = new Thread (() => {
while (!finish) {
GC.Collect ();
Thread.Yield ();
}
});
th.Start ();
th1.Start ();
Thread.Sleep (10);
for (int j = 0; j < 5 * 4 * 2; ++j) {
th.Suspend ();
Thread.Yield ();
th.Resume ();
if ((j + 1) % (5) == 0)
Console.Write ("Hello ");
if ((j + 1) % (5 * 4) == 0)
Console.WriteLine ();
}
finish = true;
th.Join ();
th1.Join ();
}
}

Output:

C# 執行緒

以上是C# 執行緒的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn