Thread.SetData(LocalDataStoreSlot, Object) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將資料設在目前執行緒的指定槽位,對應該執行緒目前的網域。 為了提升效能,建議使用標示為 屬性 ThreadStaticAttribute 的欄位。
public:
static void SetData(LocalDataStoreSlot ^ slot, System::Object ^ data);
public static void SetData(LocalDataStoreSlot slot, object? data);
public static void SetData(LocalDataStoreSlot slot, object data);
static member SetData : LocalDataStoreSlot * obj -> unit
Public Shared Sub SetData (slot As LocalDataStoreSlot, data As Object)
參數
- slot
- LocalDataStoreSlot
設定 LocalDataStoreSlot 價值的地點。
- data
- Object
要設定的價值。
範例
本節包含兩個程式代碼範例。 第一個範例展示了如何使用標有屬性 ThreadStaticAttribute 的欄位來儲存特定執行緒的資訊。 第二個例子展示了如何利用資料槽來達成同樣的效果。
第一個例子
以下範例說明如何使用標記為 的 ThreadStaticAttribute 欄位來存放特定執行緒的資訊。 此技術提供比第二個範例中展示的技術更好的性能。
using System;
using System.Threading;
class Test
{
static void Main()
{
for(int i = 0; i < 3; i++)
{
Thread newThread = new Thread(ThreadData.ThreadStaticDemo);
newThread.Start();
}
}
}
class ThreadData
{
[ThreadStatic]
static int threadSpecificData;
public static void ThreadStaticDemo()
{
// Store the managed thread id for each thread in the static
// variable.
threadSpecificData = Thread.CurrentThread.ManagedThreadId;
// Allow other threads time to execute the same code, to show
// that the static data is unique to each thread.
Thread.Sleep( 1000 );
// Display the static data.
Console.WriteLine( "Data for managed thread {0}: {1}",
Thread.CurrentThread.ManagedThreadId, threadSpecificData );
}
}
/* This code example produces output similar to the following:
Data for managed thread 4: 4
Data for managed thread 5: 5
Data for managed thread 3: 3
*/
open System
open System.Threading
type ThreadData() =
// Create a static variable to hold the data for each thread.
[<ThreadStatic; DefaultValue>]
static val mutable private threadSpecificData : int
static member ThreadStaticDemo() =
// Store the managed thread id for each thread in the static
// variable.
ThreadData.threadSpecificData <- Thread.CurrentThread.ManagedThreadId
// Allow other threads time to execute the same code, to show
// that the static data is unique to each thread.
Thread.Sleep 1000
// Display the static data.
printfn $"Data for managed thread {Thread.CurrentThread.ManagedThreadId}: {ThreadData.threadSpecificData}"
for i = 0 to 2 do
let newThread = Thread ThreadData.ThreadStaticDemo
newThread.Start()
// This code example produces output similar to the following:
// Data for managed thread 4: 4
// Data for managed thread 5: 5
// Data for managed thread 3: 3
Imports System.Threading
Class Test
<MTAThread> _
Shared Sub Main()
For i As Integer = 1 To 3
Dim newThread As New Thread(AddressOf ThreadData.ThreadStaticDemo)
newThread.Start()
Next i
End Sub
End Class
Class ThreadData
<ThreadStatic> _
Shared threadSpecificData As Integer
Shared Sub ThreadStaticDemo()
' Store the managed thread id for each thread in the static
' variable.
threadSpecificData = Thread.CurrentThread.ManagedThreadId
' Allow other threads time to execute the same code, to show
' that the static data is unique to each thread.
Thread.Sleep( 1000 )
' Display the static data.
Console.WriteLine( "Data for managed thread {0}: {1}", _
Thread.CurrentThread.ManagedThreadId, threadSpecificData )
End Sub
End Class
' This code example produces output similar to the following:
'
'Data for managed thread 4: 4
'Data for managed thread 5: 5
'Data for managed thread 3: 3
第二個例子
以下範例示範如何使用命名的資料槽來儲存執行緒特定的資訊。
using System;
using System.Threading;
class Test
{
public static void Main()
{
Thread[] newThreads = new Thread[4];
int i;
for (i = 0; i < newThreads.Length; i++)
{
newThreads[i] =
new Thread(new ThreadStart(Slot.SlotTest));
newThreads[i].Start();
}
Thread.Sleep(2000);
for (i = 0; i < newThreads.Length; i++)
{
newThreads[i].Join();
Console.WriteLine("Thread_{0} finished.",
newThreads[i].ManagedThreadId);
}
}
}
class Slot
{
private static Random randomGenerator = new Random();
public static void SlotTest()
{
// Set random data in each thread's data slot.
int slotData = randomGenerator.Next(1, 200);
int threadId = Thread.CurrentThread.ManagedThreadId;
Thread.SetData(
Thread.GetNamedDataSlot("Random"),
slotData);
// Show what was saved in the thread's data slot.
Console.WriteLine("Data stored in thread_{0}'s data slot: {1,3}",
threadId, slotData);
// Allow other threads time to execute SetData to show
// that a thread's data slot is unique to itself.
Thread.Sleep(1000);
int newSlotData =
(int)Thread.GetData(Thread.GetNamedDataSlot("Random"));
if (newSlotData == slotData)
{
Console.WriteLine("Data in thread_{0}'s data slot is still: {1,3}",
threadId, newSlotData);
}
else
{
Console.WriteLine("Data in thread_{0}'s data slot changed to: {1,3}",
threadId, newSlotData);
}
}
}
open System
open System.Threading
module Slot =
let private randomGenerator = Random()
let slotTest () =
// Set random data in each thread's data slot.
let slotData = randomGenerator.Next(1, 200)
let threadId = Thread.CurrentThread.ManagedThreadId
Thread.SetData(Thread.GetNamedDataSlot "Random", slotData)
// Show what was saved in the thread's data slot.
printfn $"Data stored in thread_{threadId}'s data slot: {slotData, 3}"
// Allow other threads time to execute SetData to show
// that a thread's data slot is unique to itself.
Thread.Sleep 1000
let newSlotData = Thread.GetData(Thread.GetNamedDataSlot "Random") :?> int
if newSlotData = slotData then
printfn $"Data in thread_{threadId}'s data slot is still: {newSlotData, 3}"
else
printfn $"Data in thread_{threadId}'s data slot changed to: {newSlotData, 3}"
let newThreads =
[| for _ = 0 to 3 do
let thread = Thread Slot.slotTest
thread.Start()
thread |]
Thread.Sleep 2000
for tread in newThreads do
tread.Join()
printfn $"Thread_{tread.ManagedThreadId} finished."
Imports System.Threading
Class Test
Public Shared Sub Main()
Dim newThreads(3) As Thread
Dim i As Integer
For i = 0 To newThreads.Length - 1
newThreads(i) = _
New Thread(New ThreadStart(AddressOf Slot.SlotTest))
newThreads(i).Start()
Next i
Thread.Sleep(2000)
For i = 0 To newThreads.Length - 1
newThreads(i).Join()
Console.WriteLine("Thread_{0} finished.", _
newThreads(i).ManagedThreadId)
Next i
End Sub
End Class
Class Slot
Private Shared randomGenerator As New Random()
Public Shared Sub SlotTest()
' Set random data in each thread's data slot.
Dim slotData As Integer = randomGenerator.Next(1, 200)
Dim threadId As Integer = Thread.CurrentThread.ManagedThreadId
Thread.SetData(
Thread.GetNamedDataSlot("Random"),
slotData)
' Show what was saved in the thread's data slot.
Console.WriteLine("Data stored in thread_{0}'s data slot: {1,3}",
threadId, slotData)
' Allow other threads time to execute SetData to show
' that a thread's data slot is unique to itself.
Thread.Sleep(1000)
Dim newSlotData As Integer = _
CType(Thread.GetData(Thread.GetNamedDataSlot("Random")), Integer)
If newSlotData = slotData Then
Console.WriteLine("Data in thread_{0}'s data slot is still: {1,3}",
threadId, newSlotData)
Else
Console.WriteLine("Data in thread_{0}'s data slot changed to: {1,3}",
threadId, newSlotData)
End If
End Sub
End Class
備註
Important
.NET Framework 提供兩種使用執行緒本地儲存(TLS)的機制:執行緒相對靜態欄位(即標有 ThreadStaticAttribute 屬性的欄位)與資料槽。 執行緒相對靜態欄位比資料插槽提供更佳的效能,並支援編譯時的類型檢查。 欲了解更多使用 TLS 的資訊,請參閱 執行緒本地儲存:Thread-Relative 靜態欄位與資料槽。
執行緒使用本地儲存記憶體機制來儲存執行緒特定的資料。 通用語言執行時會在每個程序建立時分配一個多時隙資料儲存陣列。 執行緒可以在資料儲存中分配資料槽,儲存並檢索該槽中的資料值,並在執行緒程序結束且 Thread 物件被垃圾回收後釋放該槽位供重複使用。 資料槽是每個執行緒唯一的。 其他執行緒(甚至子執行緒)無法取得這些資料。
Note
SetData 是一個 Shared 總是套用於目前執行執行緒的方法,即使你用指向另一個執行緒的變數呼叫它。 為避免混淆,呼叫 Shared 方法時請使用類別名稱: Thread.SetData(testSlot, "test data")。