Thread.Name 屬性

定義

取得或設定執行緒的名稱。Gets or sets the name of the thread.

public:
 property System::String ^ Name { System::String ^ get(); void set(System::String ^ value); };
public string Name { get; set; }
member this.Name : string with get, set
Public Property Name As String

屬性值

含有執行緒名稱的字串;如果沒有設定名稱,則為 nullA string containing the name of the thread, or null if no name was set.

例外狀況

要求了一組作業,但是早已設定了 Name 屬性。A set operation was requested, but the Name property has already been set.

範例

下列範例顯示如何為執行緒命名。The following example shows how to name a thread.

using namespace System;
using namespace System::Threading;
int main()
{
   
   // Check whether the thread has previously been named to
   // avoid a possible InvalidOperationException.
   if ( Thread::CurrentThread->Name == nullptr )
   {
      Thread::CurrentThread->Name =  "MainThread";
   }
   else
   {
      Console::WriteLine( "Unable to name a previously "
      "named thread." );
   }
}

using System;
using System.Threading;

class Name
{
    static void Main()
    {
        // Check whether the thread has previously been named
        // to avoid a possible InvalidOperationException.
        if(Thread.CurrentThread.Name == null)
        {
            Thread.CurrentThread.Name = "MainThread";
        }
        else
        {
            Console.WriteLine("Unable to name a previously " +
                "named thread.");
        }
    }
}
Imports System.Threading

Public Class Name

    <MTAThread> _
    Shared Sub Main()

        ' Check whether the thread has previously been named
        ' to avoid a possible InvalidOperationException.
        If Thread.CurrentThread.Name = Nothing Then
            Thread.CurrentThread.Name = "MainThread"
        Else
            Console.WriteLine("Unable to name a previously " & _
                "named thread.")
        End If

    End Sub
End Class

備註

此屬性為寫入一次。This property is write-once. 因為執行緒 Name 屬性的預設值是 null,所以您可以藉由與 null進行比較,判斷名稱是否已明確指派給執行緒。Because the default value of a thread's Name property is null, you can determine whether a name has already been explicitly assigned to the thread by comparing it with null.

指派給 Name 屬性的字串可以包含任何 Unicode 字元。The string assigned to the Name property can include any Unicode character.

適用於