📜  C#中的线程类

📅  最后修改于: 2021-05-29 19:26:30             🧑  作者: Mango

在C#中,多线程系统基于Thread类构建,该类封装了线程的执行。此类包含一些有助于管理和创建线程的方法和属性,并且该类在System.Threading命名空间下定义。

线程类的特点:

  • 线程类用于创建线程。
  • 借助Thread类,您可以创建前台线程和后台线程。
  • 线程类允许您设置线程的优先级。
  • 它还为您提供线程的当前状态。
  • 它提供当前执行线程的参考。
  • 这是一个密封的类,因此无法继承。

建设者

Constructor Description
Thread(ParameterizedThreadStart) Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started.
Thread(ParameterizedThreadStart, Int32) Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started and specifying the maximum stack size for the thread.
Thread(ThreadStart) Initializes a new instance of the Thread class.
Thread(ThreadStart, Int32) Initializes a new instance of the Thread class, specifying the maximum stack size for the thread.

例子:

// C# program to illustrate
// ThreadStart constructor
using System;
using System.Threading;
  
public class MXThread {
  
    // Non-static method
    public void mythr()
    {
        for (int J = 0; J < 2; J++) {
  
            Console.WriteLine("My Thread is"+
                         " in progress...!!");
        }
    }
}
  
// Driver Class
public class GFG {
  
    // Main Method
    public static void Main()
    {
        // Creating object of ExThread class
        MXThread obj = new MXThread();
  
        // Creating and initializing thread
        // Using thread class and 
        // ThreadStart constructor
        Thread t = new Thread(new ThreadStart(obj.mythr));
        t.Start();
    }
}

输出:

My Thread is in progress...!!
My Thread is in progress...!!

特性

Property Description
ApartmentState Gets or sets the apartment state of this thread.
CurrentContext Gets the current context in which the thread is executing.
CurrentCulture Gets or sets the culture for the current thread.
CurrentPrincipal Gets or sets the thread’s current principal (for role-based security).
CurrentThread Gets the currently running thread.
CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.
ExecutionContext Gets an ExecutionContext object that contains information about the various contexts of the current thread.
IsAlive Gets a value indicating the execution status of the current thread.
IsBackground Gets or sets a value indicating whether or not a thread is a background thread.
IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed thread pool.
ManagedThreadId Gets a unique identifier for the current managed thread.
Name Gets or sets the name of the thread.
Priority Gets or sets a value indicating the scheduling priority of a thread.
ThreadState Gets a value containing the states of the current thread.

例子:

// C# program to illustrate how to
// set and get the priority of threads
using System;
using System.Threading;
  
class GFG {
  
    // Main Method
    static public void Main()
    {
  
        // Creating and initializing threads
        Thread THR1 = new Thread(work);
        Thread THR2 = new Thread(work);
        Thread THR3 = new Thread(work);
  
        // Set the priority of threads
        THR2.Priority = ThreadPriority.Lowest;
        THR3.Priority = ThreadPriority.AboveNormal;
        THR1.Start();
        THR2.Start();
        THR3.Start();
  
        // Display the priority of threads
        Console.WriteLine("The priority of Thread 1 is: {0}",
                                              THR1.Priority);
  
        Console.WriteLine("The priority of Thread 2 is: {0}",
                                              THR2.Priority);
  
        Console.WriteLine("The priority of Thread 3 is: {0}",
                                              THR3.Priority);
    }
  
    public static void work()
    {
  
        // Sleep for 1 second
        Thread.Sleep(1000);
    }
}

输出:

The priority of Thread 1 is: Normal
The priority of Thread 2 is: Lowest
The priority of Thread 3 is: AboveNormal

方法

Method Description
Abort() Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
AllocateDataSlot() Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
AllocateNamedDataSlot(String) Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
BeginCriticalRegion() Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.
BeginThreadAffinity() Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.
DisableComObjectEagerCleanup() Turns off automatic cleanup of runtime callable wrappers (RCW) for the current thread.
EndCriticalRegion() Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.
EndThreadAffinity() Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.
Equals(Object) Determines whether the specified object is equal to the current object.
Finalize() Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the Thread object.
FreeNamedDataSlot(String) Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
GetApartmentState() Returns an ApartmentState value indicating the apartment state.
GetCompressedStack() Returns a CompressedStack object that can be used to capture the stack for the current thread.
GetData(LocalDataStoreSlot) Retrieves the value from the specified slot on the current thread, within the current thread’s current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
GetDomain() Returns the current domain in which the current thread is running.
GetDomainID() Returns a unique application domain identifier.
GetHashCode() Returns a hash code for the current thread.
GetNamedDataSlot(String) Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
GetType() Gets the Type of the current instance.
Interrupt() Interrupts a thread that is in the WaitSleepJoin thread state.
Join() Blocks the calling thread until the thread represented by this instance terminates, while continuing to perform standard COM and SendMessage pumping.
MemberwiseClone() Creates a shallow copy of the current Object.
MemoryBarrier() Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier() execute after memory accesses that follow the call to MemoryBarrier().
ResetAbort() Cancels an Abort(Object) requested for the current thread.
Resume() Resumes a thread that has been suspended.
SetApartmentState(ApartmentState) Sets the apartment state of a thread before it is started.
SetCompressedStack(CompressedStack) Applies a captured CompressedStack to the current thread.
SetData(LocalDataStoreSlot, Object) Sets the data in the specified slot on the currently running thread, for that thread’s current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead.
Sleep() Suspends the current thread for the specified amount of time.
SpinWait(Int32) Causes a thread to wait the number of times defined by the iterations parameter.
Start() Causes a thread to be scheduled for execution.
Suspend() Either suspends the thread, or if the thread is already suspended, has no effect.
ToString() Returns a string that represents the current object.
TrySetApartmentState(ApartmentState) Sets the apartment state of a thread before it is started.
VolatileRead() Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
VolatileWrite() Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Yield() Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.

例子:

// C# program to illustrate the
// concept of Join() method
using System;
using System.Threading;
  
public class MYThread {
  
    // Non-Static method
    public void mythr1()
    {
        Console.WriteLine("1nd thread is Working..!!");
        Thread.Sleep(100);
    }
  
    // Non-Static method
    public void mythr2()
    {
        Console.WriteLine("2nd thread is Working..!!");
    }
}
  
// Driver Class
public class ThreadExample {
  
    // Main method
    public static void Main()
    {
        // Creating instance of MYThread class
        MYThread obj = new MYThread();
  
        // Creating and initializing threads
        Thread T1 = new Thread(new ThreadStart(obj.mythr1));
        Thread T2 = new Thread(new ThreadStart(obj.mythr2));
        T1.Start();
  
        // Join thread
        T1.Join();
        T2.Start();
    }
}

输出:

1nd thread is Working..!!
2nd thread is Working..!!

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread?view=netframework-4.7.2#thread-safety