System.Threading.Thread sınıfı

Bu makale, bu API'nin başvuru belgelerine ek açıklamalar sağlar.

Thread sınıfı bir iş parçacığı oluşturur ve denetler, önceliğini ayarlar ve durumunu alır.

Bir işlem başladığında, ortak dil çalışma zamanı otomatik olarak uygulama kodunu yürütmek için tek bir ön plan iş parçacığı oluşturur. Bu ana ön plan iş parçacığıyla birlikte bir işlem, işlemle ilişkili program kodunun bir bölümünü yürütmek için bir veya daha fazla iş parçacığı oluşturabilir. Bu iş parçacıkları ön planda veya arka planda yürütülebilir. Ayrıca, ortak dil çalışma zamanı tarafından yönetilen çalışan iş parçacıklarında kod yürütmek için sınıfını kullanabilirsiniz ThreadPool .

İş parçacığı başlatma

bir iş parçacığını, iş parçacığının sınıf oluşturucusunda yürütülecek yöntemini temsil eden bir temsilci sağlayarak başlatırsınız. Ardından yürütmeye Start başlamak için yöntemini çağırırsınız.

Oluşturucular Thread , yürütülecek yönteme bir bağımsız değişken geçirip geçiremeyeceğiniz bağlı olarak iki temsilci türünden birini alabilir:

  • Yöntemin bağımsız değişkeni yoksa, oluşturucuya bir ThreadStart temsilci geçirirsiniz. İmzaya sahiptir:

    public delegate void ThreadStart()
    
    Public Delegate Sub ThreadStart()
    

    Aşağıdaki örnek, yöntemini yürüten ExecuteInForeground bir iş parçacığı oluşturur ve başlatır. yöntemi, bazı iş parçacığı özellikleri hakkındaki bilgileri görüntüler, ardından yarım saniye boyunca duraklatıldığı ve geçen saniye sayısını görüntüleyen bir döngü yürütür. İş parçacığı en az beş saniye boyunca yürütürse döngü sona erer ve iş parçacığı yürütmeyi sonlandırır.

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    public class Example2
    {
       public static void Main()
       {
          var th = new Thread(ExecuteInForeground);
          th.Start();
          Thread.Sleep(1000);
          Console.WriteLine("Main thread ({0}) exiting...",
                            Thread.CurrentThread.ManagedThreadId);
       }
    
       private static void ExecuteInForeground()
       {
          var sw = Stopwatch.StartNew();
          Console.WriteLine("Thread {0}: {1}, Priority {2}",
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority);
          do {
             Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000.0);
             Thread.Sleep(500);
          } while (sw.ElapsedMilliseconds <= 5000);
          sw.Stop();
       }
    }
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.51 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.02 seconds
    //       Thread 3: Elapsed 1.53 seconds
    //       Thread 3: Elapsed 2.05 seconds
    //       Thread 3: Elapsed 2.55 seconds
    //       Thread 3: Elapsed 3.07 seconds
    //       Thread 3: Elapsed 3.57 seconds
    //       Thread 3: Elapsed 4.07 seconds
    //       Thread 3: Elapsed 4.58 seconds
    
    open System.Diagnostics
    open System.Threading
    
    let executeInForeground () =
        let sw = Stopwatch.StartNew()
    
        printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: {Thread.CurrentThread.ThreadState}, Priority {Thread.CurrentThread.Priority}"
    
        while sw.ElapsedMilliseconds <= 5000 do
            printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: Elapsed {sw.ElapsedMilliseconds / 1000L:N2} seconds"
            Thread.Sleep 500
    
        sw.Stop()
    
    let th = Thread executeInForeground
    th.Start()
    Thread.Sleep 1000
    printfn $"Main thread ({Thread.CurrentThread.ManagedThreadId}) exiting..."
    
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.51 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.02 seconds
    //       Thread 3: Elapsed 1.53 seconds
    //       Thread 3: Elapsed 2.05 seconds
    //       Thread 3: Elapsed 2.55 seconds
    //       Thread 3: Elapsed 3.07 seconds
    //       Thread 3: Elapsed 3.57 seconds
    //       Thread 3: Elapsed 4.07 seconds
    //       Thread 3: Elapsed 4.58 seconds
    
    Imports System.Diagnostics
    Imports System.Threading
    
    Module Example3
        Public Sub Main()
            Dim th As New Thread(AddressOf ExecuteInForeground)
            th.Start()
            Thread.Sleep(1000)
            Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId)
        End Sub
    
        Private Sub ExecuteInForeground()
            Dim start As DateTime = DateTime.Now
            Dim sw As Stopwatch = Stopwatch.StartNew()
            Console.WriteLine("Thread {0}: {1}, Priority {2}",
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority)
            Do
                Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000)
                Thread.Sleep(500)
            Loop While sw.ElapsedMilliseconds <= 5000
            sw.Stop()
        End Sub
    End Module
    ' The example displays output like the following:
    '       Thread 3: Running, Priority Normal
    '       Thread 3: Elapsed 0.00 seconds
    '       Thread 3: Elapsed 0.51 seconds
    '       Main thread (1) exiting...
    '       Thread 3: Elapsed 1.02 seconds
    '       Thread 3: Elapsed 1.53 seconds
    '       Thread 3: Elapsed 2.05 seconds
    '       Thread 3: Elapsed 2.55 seconds
    '       Thread 3: Elapsed 3.07 seconds
    '       Thread 3: Elapsed 3.57 seconds
    '       Thread 3: Elapsed 4.07 seconds
    '       Thread 3: Elapsed 4.58 seconds
    
  • Yöntemin bağımsız değişkeni varsa, oluşturucuya bir ParameterizedThreadStart temsilci geçirirsiniz. İmzaya sahiptir:

    public delegate void ParameterizedThreadStart(object obj)
    
    Public Delegate Sub ParameterizedThreadStart(obj As Object)
    

    Temsilci tarafından yürütülen yöntem daha sonra parametreyi uygun türe dönüştürebilir (C# dilinde) veya dönüştürebilir (Visual Basic'te).

    Aşağıdaki örnek, oluşturucuyu çağırması dışında önceki örnekle Thread(ParameterizedThreadStart) aynıdır. Yöntemin bu sürümünde, döngünün ExecuteInForeground yürütülecek yaklaşık milisaniye sayısını temsil eden tek bir parametre vardır.

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    public class Example3
    {
       public static void Main()
       {
          var th = new Thread(ExecuteInForeground);
          th.Start(4500);
          Thread.Sleep(1000);
          Console.WriteLine("Main thread ({0}) exiting...",
                            Thread.CurrentThread.ManagedThreadId);
       }
    
       private static void ExecuteInForeground(Object obj)
       {
          int interval;
          try {
             interval = (int) obj;
          }
          catch (InvalidCastException) {
             interval = 5000;
          }
          var sw = Stopwatch.StartNew();
          Console.WriteLine("Thread {0}: {1}, Priority {2}",
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority);
          do {
             Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000.0);
             Thread.Sleep(500);
          } while (sw.ElapsedMilliseconds <= interval);
          sw.Stop();
       }
    }
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.52 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.03 seconds
    //       Thread 3: Elapsed 1.55 seconds
    //       Thread 3: Elapsed 2.06 seconds
    //       Thread 3: Elapsed 2.58 seconds
    //       Thread 3: Elapsed 3.09 seconds
    //       Thread 3: Elapsed 3.61 seconds
    //       Thread 3: Elapsed 4.12 seconds
    
    open System
    open System.Diagnostics
    open System.Threading
    
    let executeInForeground obj =
        let interval =
            try
                unbox<int> obj
            with :? InvalidCastException ->
                5000
    
        let sw = Stopwatch.StartNew()
    
        printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: {Thread.CurrentThread.ThreadState}, Priority {Thread.CurrentThread.Priority}"
    
        while sw.ElapsedMilliseconds <= interval do
            printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: Elapsed {sw.ElapsedMilliseconds / 1000L:N2} seconds"
            Thread.Sleep 500
    
        sw.Stop()
    
    let th = Thread(ParameterizedThreadStart executeInForeground)
    th.Start 4500
    Thread.Sleep 1000
    printfn $"Main thread ({Thread.CurrentThread.ManagedThreadId}) exiting..."
    
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.52 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.03 seconds
    //       Thread 3: Elapsed 1.55 seconds
    //       Thread 3: Elapsed 2.06 seconds
    //       Thread 3: Elapsed 2.58 seconds
    //       Thread 3: Elapsed 3.09 seconds
    //       Thread 3: Elapsed 3.61 seconds
    //       Thread 3: Elapsed 4.12 seconds
    
    Imports System.Diagnostics
    Imports System.Threading
    
    Module Example4
        Public Sub Main()
            Dim th As New Thread(AddressOf ExecuteInForeground)
            th.Start(4500)
            Thread.Sleep(1000)
            Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId)
        End Sub
    
        Private Sub ExecuteInForeground(obj As Object)
            Dim interval As Integer
            If IsNumeric(obj) Then
                interval = CInt(obj)
            Else
                interval = 5000
            End If
            Dim start As DateTime = DateTime.Now
            Dim sw As Stopwatch = Stopwatch.StartNew()
            Console.WriteLine("Thread {0}: {1}, Priority {2}",
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority)
            Do
                Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000)
                Thread.Sleep(500)
            Loop While sw.ElapsedMilliseconds <= interval
            sw.Stop()
        End Sub
    End Module
    ' The example displays output like the following:
    '       Thread 3: Running, Priority Normal
    '       Thread 3: Elapsed 0.00 seconds
    '       Thread 3: Elapsed 0.52 seconds
    '       Main thread (1) exiting...
    '       Thread 3: Elapsed 1.03 seconds
    '       Thread 3: Elapsed 1.55 seconds
    '       Thread 3: Elapsed 2.06 seconds
    '       Thread 3: Elapsed 2.58 seconds
    '       Thread 3: Elapsed 3.09 seconds
    '       Thread 3: Elapsed 3.61 seconds
    '       Thread 3: Elapsed 4.12 seconds
    

İş parçacığını başlattıktan sonra nesne Thread başvurusunun korunması gerekmez. İş parçacığı yordamı tamamlanana kadar iş parçacığı yürütülmeye devam eder.

İş Parçacığı nesnelerini alma

İş parçacığının yürüttüğü koddan şu anda yürütülen iş parçacığına başvuru almak için static (Shared Visual Basic'te) CurrentThread özelliğini kullanabilirsiniz. Aşağıdaki örnek, ana uygulama iş parçacığı, başka bir ön plan iş parçacığı, bir arka plan iş parçacığı ve iş parçacığı havuzu iş parçacığı hakkında bilgi görüntülemek için özelliğini kullanır CurrentThread .

using System;
using System.Threading;

public class Example1
{
   static Object obj = new Object();
   
   public static void Main()
   {
      ThreadPool.QueueUserWorkItem(ShowThreadInformation);
      var th1 = new Thread(ShowThreadInformation);
      th1.Start();
      var th2 = new Thread(ShowThreadInformation);
      th2.IsBackground = true;
      th2.Start();
      Thread.Sleep(500);
      ShowThreadInformation(null); 
   }
   
   private static void ShowThreadInformation(Object state)
   {
      lock (obj) {
         var th  = Thread.CurrentThread;
         Console.WriteLine("Managed thread #{0}: ", th.ManagedThreadId);
         Console.WriteLine("   Background thread: {0}", th.IsBackground);
         Console.WriteLine("   Thread pool thread: {0}", th.IsThreadPoolThread);
         Console.WriteLine("   Priority: {0}", th.Priority);
         Console.WriteLine("   Culture: {0}", th.CurrentCulture.Name);
         Console.WriteLine("   UI culture: {0}", th.CurrentUICulture.Name);
         Console.WriteLine();
      }   
   }
}
// The example displays output like the following:
//       Managed thread #6:
//          Background thread: True
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #3:
//          Background thread: True
//          Thread pool thread: True
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #4:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #1:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
open System.Threading

let obj = obj ()

let showThreadInformation (state: obj) =
    lock obj (fun () ->
        let th = Thread.CurrentThread
        printfn $"Managed thread #{th.ManagedThreadId}: "
        printfn $"   Background thread: {th.IsBackground}"
        printfn $"   Thread pool thread: {th.IsThreadPoolThread}"
        printfn $"   Priority: {th.Priority}"
        printfn $"   Culture: {th.CurrentCulture.Name}"
        printfn $"   UI culture: {th.CurrentUICulture.Name}"
        printfn "")

ThreadPool.QueueUserWorkItem showThreadInformation |> ignore
let th1 = Thread(ParameterizedThreadStart showThreadInformation)
th1.Start()
let th2 = Thread(ParameterizedThreadStart showThreadInformation)
th2.IsBackground <- true
th2.Start()
Thread.Sleep 500
showThreadInformation ()

// The example displays output like the following:
//       Managed thread #6:
//          Background thread: True
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//
//       Managed thread #3:
//          Background thread: True
//          Thread pool thread: True
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//
//       Managed thread #4:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//
//       Managed thread #1:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
Imports System.Threading

Module Example2
    Private lock As New Object()

    Public Sub Main()
        ThreadPool.QueueUserWorkItem(AddressOf ShowThreadInformation)
        Dim th1 As New Thread(AddressOf ShowThreadInformation)
        th1.Start()
        Dim th2 As New Thread(AddressOf ShowThreadInformation)
        th2.IsBackground = True
        th2.Start()
        Thread.Sleep(500)
        ShowThreadInformation(Nothing)
    End Sub

    Private Sub ShowThreadInformation(state As Object)
        SyncLock lock
            Dim th As Thread = Thread.CurrentThread
            Console.WriteLine("Managed thread #{0}: ", th.ManagedThreadId)
            Console.WriteLine("   Background thread: {0}", th.IsBackground)
            Console.WriteLine("   Thread pool thread: {0}", th.IsThreadPoolThread)
            Console.WriteLine("   Priority: {0}", th.Priority)
            Console.WriteLine("   Culture: {0}", th.CurrentCulture.Name)
            Console.WriteLine("   UI culture: {0}", th.CurrentUICulture.Name)
            Console.WriteLine()
        End SyncLock
    End Sub
End Module
' The example displays output like the following:
'       ' Managed thread #6:
'          Background thread: True
'          Thread pool thread: False
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US
'       
'       Managed thread #3:
'          Background thread: True
'          Thread pool thread: True
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US
'       
'       Managed thread #4:
'          Background thread: False
'          Thread pool thread: False
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US
'       
'       Managed thread #1:
'          Background thread: False
'          Thread pool thread: False
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US

Ön plan ve arka plan iş parçacıkları

sınıfının örnekleri Thread ön plan iş parçacıklarını veya arka plan iş parçacıklarını temsil eder. Arka plan iş parçacıkları tek bir özel durumla ön plan iş parçacıklarıyla aynıdır: tüm ön plan iş parçacıkları sonlandırıldıysa arka plan iş parçacığı bir işlemi çalışır durumda tutmaz. Tüm ön plan iş parçacıkları durdurulduktan sonra çalışma zamanı tüm arka plan iş parçacıklarını durdurur ve kapanır.

Varsayılan olarak, aşağıdaki iş parçacıkları ön planda yürütülür:

  • Ana uygulama iş parçacığı.

  • Sınıf Thread oluşturucu çağrılarak oluşturulan tüm iş parçacıkları.

Aşağıdaki iş parçacıkları varsayılan olarak arka planda yürütülür:

  • İş parçacığı havuzu iş parçacıkları, çalışma zamanı tarafından tutulan bir çalışan iş parçacıkları havuzundan gelir. sınıfını kullanarak ThreadPool iş parçacığı havuzunu yapılandırabilir ve iş parçacığı havuzu iş parçacıkları üzerinde çalışma zamanlayabilirsiniz.

    Not

    Görev tabanlı zaman uyumsuz işlemler iş parçacığı havuzu iş parçacıklarında otomatik olarak yürütülür. Görev tabanlı zaman uyumsuz işlemler, görev tabanlı zaman uyumsuz deseni uygulamak için ve Task<TResult> sınıflarını kullanırTask.

  • Yönetilmeyen koddan yönetilen yürütme ortamına giren tüm iş parçacıkları.

İstediğiniz zaman özelliğini ayarlayarak arka planda yürütülecek bir iş parçacığını IsBackground değiştirebilirsiniz. Arka plan iş parçacıkları, bir uygulama çalıştığı sürece devam etmesi gereken ancak dosya sistemi değişikliklerini veya gelen yuva bağlantılarını izleme gibi uygulamanın sonlandırılmasını engellememesi gereken işlemler için kullanışlıdır.

Aşağıdaki örnekte ön plan ve arka plan iş parçacıkları arasındaki fark gösterilmektedir. İş parçacığı başlatma bölümündeki ilk örnek gibidir, ancak iş parçacığını başlatmadan önce arka planda yürütülecek şekilde ayarlar. Çıktıda gösterildiği gibi, döngü beş saniye boyunca yürütülmeden önce kesilir.

using System;
using System.Diagnostics;
using System.Threading;

public class Example
{
   public static void Main()
   {
      var th = new Thread(ExecuteInForeground);
      th.IsBackground = true;
      th.Start();
      Thread.Sleep(1000);
      Console.WriteLine("Main thread ({0}) exiting...",
                        Thread.CurrentThread.ManagedThreadId);
   }

   private static void ExecuteInForeground()
   {
      var sw = Stopwatch.StartNew();
      Console.WriteLine("Thread {0}: {1}, Priority {2}",
                        Thread.CurrentThread.ManagedThreadId,
                        Thread.CurrentThread.ThreadState,
                        Thread.CurrentThread.Priority);
      do {
         Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                           Thread.CurrentThread.ManagedThreadId,
                           sw.ElapsedMilliseconds / 1000.0);
         Thread.Sleep(500);
      } while (sw.ElapsedMilliseconds <= 5000);
      sw.Stop();
   }
}
// The example displays output like the following:
//       Thread 3: Background, Priority Normal
//       Thread 3: Elapsed 0.00 seconds
//       Thread 3: Elapsed 0.51 seconds
//       Main thread (1) exiting...
open System.Diagnostics
open System.Threading

let executeInForeground () =
    let sw = Stopwatch.StartNew()
    printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: {Thread.CurrentThread.ThreadState}, Priority {Thread.CurrentThread.Priority}"
    while sw.ElapsedMilliseconds <= 5000 do
        printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: Elapsed {sw.ElapsedMilliseconds / 1000L:N2} seconds"
        Thread.Sleep 500
    sw.Stop()

let th = Thread executeInForeground
th.IsBackground <- true
th.Start()
Thread.Sleep 1000
printfn $"Main thread ({Thread.CurrentThread.ManagedThreadId}) exiting..."

// The example displays output like the following:
//       Thread 3: Background, Priority Normal
//       Thread 3: Elapsed 0.00 seconds
//       Thread 3: Elapsed 0.51 seconds
//       Main thread (1) exiting...
Imports System.Diagnostics
Imports System.Threading

Module Example1
    Public Sub Main()
        Dim th As New Thread(AddressOf ExecuteInForeground)
        th.IsBackground = True
        th.Start()
        Thread.Sleep(1000)
        Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId)
    End Sub

    Private Sub ExecuteInForeground()
        Dim start As DateTime = DateTime.Now
        Dim sw As Stopwatch = Stopwatch.StartNew()
        Console.WriteLine("Thread {0}: {1}, Priority {2}",
                        Thread.CurrentThread.ManagedThreadId,
                        Thread.CurrentThread.ThreadState,
                        Thread.CurrentThread.Priority)
        Do
            Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                           Thread.CurrentThread.ManagedThreadId,
                           sw.ElapsedMilliseconds / 1000)
            Thread.Sleep(500)
        Loop While sw.ElapsedMilliseconds <= 5000
        sw.Stop()
    End Sub
End Module
' The example displays output like the following:
'       Thread 3: Background, Priority Normal
'       Thread 3: Elapsed 0.00 seconds
'       Thread 3: Elapsed 0.51 seconds
'       Main thread (1) exiting...

Kültür ve iş parçacıkları

Her iş parçacığı, özelliğiyle temsil edilen bir kültüre CurrentCulture ve özelliğiyle temsil edilen bir UI kültürüne CurrentUICulture sahiptir. Geçerli kültür ayrıştırma ve biçimlendirme, dize karşılaştırma ve sıralama gibi kültüre duyarlı işlemleri destekler ve ayrıca bir iş parçacığı tarafından kullanılan yazma sistemini ve takvimi denetler. Geçerli kullanıcı arabirimi kültürü, kaynak dosyalarındaki kaynakların kültüre duyarlı alınmasını sağlar.

Önemli

CurrentCulture ve CurrentUICulture özellikleri, geçerli iş parçacığı dışında herhangi bir iş parçacığıyla kullanıldığında güvenilir bir şekilde çalışmaz. .NET Framework'te bu özellikleri okumak güvenilirdir, ancak bu özellikleri geçerli iş parçacığı dışında bir iş parçacığı için ayarlamak güvenilir değildir. .NET Core'da, InvalidOperationException bir iş parçacığı bu özellikleri farklı bir iş parçacığında okumaya veya yazmaya çalışırsa oluşturulur. Geçerli kültürü almak ve ayarlamak için ve CultureInfo.CurrentUICulture özelliklerini kullanmanızı CultureInfo.CurrentCulture öneririz.

Yeni bir iş parçacığı örneği oluşturulduğunda, onun kültürü ve ui kültürü, yeni iş parçacığının oluşturulduğu iş parçacığının kültürü ve ui kültürü tarafından değil geçerli sistem kültürü ve UI kültürü tarafından tanımlanır. Bu, örneğin, geçerli sistem kültürünün İngilizce (Birleşik Devletler) ve birincil uygulama iş parçacığının geçerli kültürünün Fransızca (Fransa) olması durumunda, oluşturucuyu birincil iş parçacığından çağırarak Thread(ParameterizedThreadStart) oluşturulan yeni iş parçacığının kültürünün Fransızca (Fransa) değil İngilizce (Birleşik Devletler) olduğu anlamına gelir. Daha fazla bilgi için sınıf konusunun "Kültür ve iş parçacıkları" bölümüne CultureInfo bakın.

Önemli

Bu, .NET Framework 4.6 ve sonraki sürümleri hedefleyen uygulamalar için zaman uyumsuz işlemler yürüten iş parçacıkları için geçerli değildir. Bu durumda, kültür ve ui kültürü zaman uyumsuz bir işlemin bağlamının bir parçasıdır; zaman uyumsuz bir işlemin varsayılan olarak yürütüldiği iş parçacığı, zaman uyumsuz işlemin başlatıldığı iş parçacığının kültürünü ve ui kültürünü devralır. Daha fazla bilgi için sınıf açıklamalarının "Kültür ve görev tabanlı zaman uyumsuz işlemler" bölümüne CultureInfo bakın.

Bir uygulamada yürütülen tüm iş parçacıklarının aynı kültürü ve ui kültürünü paylaştığından emin olmak için aşağıdakilerden birini yapabilirsiniz:

Daha fazla bilgi ve örnek için sınıf açıklamalarının "Kültür ve iş parçacıkları" bölümüne CultureInfo bakın.

İş parçacıkları hakkında bilgi alma ve iş parçacıklarını denetleme

bir iş parçacığı hakkında bilgi sağlayan bir dizi özellik değeri alabilirsiniz. Bazı durumlarda, iş parçacığının işlemini denetlemek için bu özellik değerlerini de ayarlayabilirsiniz. Bu iş parçacığı özellikleri şunlardır:

  • Bir ad. Name bir iş parçacığını tanımlamak için kullanabileceğiniz bir kez yazma özelliğidir. Varsayılan değeridir null.

  • yöntemini çağırarak GetHashCode alabildiğiniz bir karma kodu. Karma kod, bir iş parçacığını benzersiz olarak tanımlamak için kullanılabilir; iş parçacığınızın ömrü boyunca karma kodu, değeri aldığınız uygulama etki alanından bağımsız olarak başka bir iş parçacığının değeriyle harmanlanmaz.

  • İş parçacığı kimliği. Salt okunur ManagedThreadId özelliğinin değeri çalışma zamanı tarafından atanır ve işlemi içindeki bir iş parçacığını benzersiz olarak tanımlar.

    Not

    Yönetilmeyen bir konak yönetilen ve yönetilmeyen iş parçacıkları arasındaki ilişkiyi denetleyebildiğinden, işletim sistemi ThreadId'sinin yönetilen iş parçacığıyla sabit bir ilişkisi yoktur. Özellikle, karmaşık bir konak aynı işletim sistemi iş parçacığına karşı birçok yönetilen iş parçacığı zamanlamak veya yönetilen iş parçacığını farklı işletim sistemi iş parçacıkları arasında taşımak için CLR Barındırma API'sini kullanabilir.

  • İş parçacığının geçerli durumu. Varlığı boyunca, bir iş parçacığı her zaman özelliği tarafından ThreadState tanımlanan bir veya daha fazla durumda olur.

  • Özelliği tarafından ThreadPriority tanımlanan bir zamanlama öncelik düzeyi. Bir iş parçacığının önceliğini istemek için bu değeri ayarlayabilirsiniz, ancak işletim sistemi tarafından kabul edilmesi garanti edilmez.

  • bir iş parçacığının iş parçacığı havuzu iş parçacığı olup olmadığını gösteren salt okunur IsThreadPoolThread özelliği.

  • IsBackground özelliği. Daha fazla bilgi için Ön plan ve arka plan iş parçacıkları bölümüne bakın.

Örnekler

Aşağıdaki örnekte basit iş parçacığı işlevselliği gösterilmektedir.

using System;
using System.Threading;

// Simple threading scenario:  Start a static method running
// on a second thread.
public class ThreadExample {
    // The ThreadProc method is called when the thread starts.
    // It loops ten times, writing to the console and yielding
    // the rest of its time slice each time, and then ends.
    public static void ThreadProc() {
        for (int i = 0; i < 10; i++) {
            Console.WriteLine("ThreadProc: {0}", i);
            // Yield the rest of the time slice.
            Thread.Sleep(0);
        }
    }

    public static void Main() {
        Console.WriteLine("Main thread: Start a second thread.");
        // The constructor for the Thread class requires a ThreadStart
        // delegate that represents the method to be executed on the
        // thread.  C# simplifies the creation of this delegate.
        Thread t = new Thread(new ThreadStart(ThreadProc));

        // Start ThreadProc.  Note that on a uniprocessor, the new
        // thread does not get any processor time until the main thread
        // is preempted or yields.  Uncomment the Thread.Sleep that
        // follows t.Start() to see the difference.
        t.Start();
        //Thread.Sleep(0);

        for (int i = 0; i < 4; i++) {
            Console.WriteLine("Main thread: Do some work.");
            Thread.Sleep(0);
        }

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
        t.Join();
        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
        Console.ReadLine();
    }
}
open System.Threading

// Simple threading scenario:  Start a static method running
// on a second thread.

// The ThreadProc method is called when the thread starts.
// It loops ten times, writing to the console and yielding
// the rest of its time slice each time, and then ends.
let threadProc () =
    for i = 0 to 9 do
        printfn $"ThreadProc: {i}"
        // Yield the rest of the time slice.
        Thread.Sleep 0

printfn "Main thread: Start a second thread."
// The constructor for the Thread class requires a ThreadStart
// delegate that represents the method to be executed on the
// thread. F# simplifies the creation of this delegate.
let t = Thread threadProc

// Start ThreadProc.  Note that on a uniprocessor, the new
// thread does not get any processor time until the main thread
// is preempted or yields.  Uncomment the Thread.Sleep that
// follows t.Start() to see the difference.
t.Start()
//Thread.Sleep 0

for _ = 0 to 3 do
    printfn "Main thread: Do some work."
    Thread.Sleep 0

printfn "Main thread: Call Join(), to wait until ThreadProc ends."
t.Join()
printfn "Main thread: ThreadProc.Join has returned.  Press Enter to end program."
stdin.ReadLine() |> ignore
Imports System.Threading

' Simple threading scenario:  Start a Shared method running
' on a second thread.
Public Class ThreadExample
    ' The ThreadProc method is called when the thread starts.
    ' It loops ten times, writing to the console and yielding 
    ' the rest of its time slice each time, and then ends.
    Public Shared Sub ThreadProc()
        Dim i As Integer
        For i = 0 To 9
            Console.WriteLine("ThreadProc: {0}", i)
            ' Yield the rest of the time slice.
            Thread.Sleep(0)
        Next
    End Sub

    Public Shared Sub Main()
        Console.WriteLine("Main thread: Start a second thread.")
        ' The constructor for the Thread class requires a ThreadStart 
        ' delegate.  The Visual Basic AddressOf operator creates this
        ' delegate for you.
        Dim t As New Thread(AddressOf ThreadProc)

        ' Start ThreadProc.  Note that on a uniprocessor, the new 
        ' thread does not get any processor time until the main thread 
        ' is preempted or yields.  Uncomment the Thread.Sleep that 
        ' follows t.Start() to see the difference.
        t.Start()
        'Thread.Sleep(0)

        Dim i As Integer
        For i = 1 To 4
            Console.WriteLine("Main thread: Do some work.")
            Thread.Sleep(0)
        Next

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.")
        t.Join()
        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.")
        Console.ReadLine()
    End Sub
End Class

Bu kod aşağıdakine benzer bir çıkış oluşturur:

[VB, C++, C#]
Main thread: Start a second thread.
Main thread: Do some work.
ThreadProc: 0
Main thread: Do some work.
ThreadProc: 1
Main thread: Do some work.
ThreadProc: 2
Main thread: Do some work.
ThreadProc: 3
Main thread: Call Join(), to wait until ThreadProc ends.
ThreadProc: 4
ThreadProc: 5
ThreadProc: 6
ThreadProc: 7
ThreadProc: 8
ThreadProc: 9
Main thread: ThreadProc.Join has returned. Press Enter to end program.