Thread.SetData 方法

在当前正在运行的线程上为此线程的当前域在指定槽中设置数据。

**命名空间:**System.Threading
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
Public Shared Sub SetData ( _
    slot As LocalDataStoreSlot, _
    data As Object _
)
用法
Dim slot As LocalDataStoreSlot
Dim data As Object

Thread.SetData(slot, data)
public static void SetData (
    LocalDataStoreSlot slot,
    Object data
)
public:
static void SetData (
    LocalDataStoreSlot^ slot, 
    Object^ data
)
public static void SetData (
    LocalDataStoreSlot slot, 
    Object data
)
public static function SetData (
    slot : LocalDataStoreSlot, 
    data : Object
)

参数

  • data
    要设置的值。

备注

提示

应用于此方法的 HostProtectionAttribute 属性 (attribute) 具有以下 Resources 属性 (property) 值:SharedState | ExternalThreadingHostProtectionAttribute 不影响桌面应用程序(这些应用程序通常通过双击图标、键入命令或在浏览器中输入 URL 来启动)。有关更多信息,请参见 HostProtectionAttribute 类或 SQL Server 编程和宿主保护属性

线程使用本地存储内存机制来存储线程特定的数据。公共语言运行库在创建每个进程时给它分配一个多槽数据存储区数组。线程可分配数据存储区中的数据槽、在数据槽中存储和检索数据值,并在线程过程结束且垃圾回收回收了 Thread 对象后释放数据槽以供重用。数据槽对于每个线程是唯一的。其他任何线程(即使是子线程)都无法获取这些数据。

提示

SetDataShared 方法,它始终应用于当前执行的线程,即使用引用另一个线程的变量调用它。为避免混淆,请在调用 Shared 方法时使用类名:Thread.SetData(testSlot, "test data")

示例

下面的代码示例阐释了如何使用命名的数据槽存储线程特定的信息。

Option Explicit
Option Strict

Imports System
Imports System.Threading

Class Test

    <MTAThread> _
    Shared Sub Main()
        Dim newThreads(3) As Thread
        For i As Integer = 0 To newThreads.Length - 1
            newThreads(i) = New Thread(AddressOf SlotExample.SlotTest)
            newThreads(i).Start()
        Next i
    End Sub
    
End Class

Public Class SlotExample

    Shared randomGenerator As Random = New Random()

    Shared Sub SlotTest()
    
        ' Set different data in each thread's data slot.
        Thread.SetData( _
            Thread.GetNamedDataSlot("Random"), _ 
            randomGenerator.Next(1, 200))

        ' Write the data from each thread's data slot.
        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", _
            AppDomain.GetCurrentThreadId().ToString(), _
            Thread.GetData( _
            Thread.GetNamedDataSlot("Random")).ToString())

        ' Allow other threads time to execute SetData to show
        ' that a thread's data slot is unique to the thread.
        Thread.Sleep(1000)

        Console.WriteLine("Data in thread_{0}'s data slot is still: {1,3}", _
            AppDomain.GetCurrentThreadId().ToString(), _
            Thread.GetData( _
            Thread.GetNamedDataSlot("Random")).ToString())

        ' Allow time for other threads to show their data,
        ' then demonstrate that any code a thread executes
        ' has access to the thread's named data slot.        
        Thread.Sleep(1000)

        Dim o As New Other()
        o.ShowSlotData()
    End Sub
    
End Class

Public Class Other
    Public Sub ShowSlotData()
        ' This method has no access to the data in the SlotExample
        ' class, but when executed by a thread it can obtain
        ' the thread's data from a named slot.
        Console.WriteLine("Other code displays data in thread_{0}'s data slot: {1,3}", _
            AppDomain.GetCurrentThreadId().ToString(), _
            Thread.GetData( _
            Thread.GetNamedDataSlot("Random")).ToString())
    End Sub
End Class
using System;
using System.Threading;

class Test
{
    static void Main()
    {
        Thread[] newThreads = new Thread[4];
        for(int i = 0; i < newThreads.Length; i++)
        {
            newThreads[i] = 
                new Thread(new ThreadStart(Slot.SlotTest));
            newThreads[i].Start();
        }
    }
}

class Slot
{
    static Random randomGenerator = new Random();

    public static void SlotTest()
    {
        // Set different data in each thread's data slot.
        Thread.SetData(
            Thread.GetNamedDataSlot("Random"), 
            randomGenerator.Next(1, 200));

        // Write the data from each thread's data slot.
        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", 
            AppDomain.GetCurrentThreadId().ToString(),
            Thread.GetData(
            Thread.GetNamedDataSlot("Random")).ToString());

        // Allow other threads time to execute SetData to show
        // that a thread's data slot is unique to the thread.
        Thread.Sleep(1000);

        Console.WriteLine("Data in thread_{0}'s data slot is still: {1,3}", 
            AppDomain.GetCurrentThreadId().ToString(),
            Thread.GetData(
            Thread.GetNamedDataSlot("Random")).ToString());

        // Allow time for other threads to show their data,
        // then demonstrate that any code a thread executes
        // has access to the thread's named data slot.        
        Thread.Sleep(1000);

        Other o = new Other();
        o.ShowSlotData();
    }
}

public class Other
{
    public void ShowSlotData()
    {
        // This method has no access to the data in the Slot
        // class, but when executed by a thread it can obtain
        // the thread's data from a named slot.
        Console.WriteLine("Other code displays data in thread_{0}'s data slot: {1,3}", 
            AppDomain.GetCurrentThreadId().ToString(), 
            Thread.GetData( 
            Thread.GetNamedDataSlot("Random")).ToString());
    }
}
using namespace System;
using namespace System::Threading;
ref class Other
{
public:
   void ShowSlotData()
   {
      
      // This method has no access to the data in the Slot
      // class, but when executed by a thread it can obtain
      // the thread's data from a named slot.
      Console::WriteLine(  "Other code displays data in thread_{0}'s data slot: {1,3}", AppDomain::GetCurrentThreadId(), Thread::GetData( Thread::GetNamedDataSlot(  "Random" ) )->ToString() );
   }

};

ref class Slot
{
private:
   static Random^ randomGenerator = gcnew Random;

public:
   static void SlotTest()
   {
      
      // Set different data in each thread's data slot.
      Thread::SetData( Thread::GetNamedDataSlot( "Random" ), randomGenerator->Next( 1, 200 ) );
      
      // Write the data from each thread's data slot.
      Console::WriteLine( "Data in thread_{0}'s data slot: {1,3}", AppDomain::GetCurrentThreadId().ToString(), Thread::GetData( Thread::GetNamedDataSlot( "Random" ) )->ToString() );
      
      // Allow other threads time to execute SetData to show
      // that a thread's data slot is unique to the thread.
      Thread::Sleep( 1000 );
      Console::WriteLine( "Data in thread_{0}'s data slot is still: {1,3}", AppDomain::GetCurrentThreadId().ToString(), Thread::GetData( Thread::GetNamedDataSlot( "Random" ) )->ToString() );
      
      // Allow time for other threads to show their data,
      // then demonstrate that any code a thread executes
      // has access to the thread's named data slot.        
      Thread::Sleep( 1000 );
      Other^ o = gcnew Other;
      o->ShowSlotData();
   }

};

int main()
{
   array<Thread^>^newThreads = gcnew array<Thread^>(4);
   for ( int i = 0; i < newThreads->Length; i++ )
   {
      newThreads[ i ] = gcnew Thread( gcnew ThreadStart( &Slot::SlotTest ) );
      newThreads[ i ]->Start();

   }
}
import System.*;
import System.Threading.*;
import System.Threading.Thread;

class Test
{
    public static void main(String[] args)
    {
        Thread newThreads[] = new Thread[4];

        for (int i = 0; i < newThreads.length; i++) {
            newThreads[i] = new Thread(new ThreadStart(Slot.SlotTest));
            newThreads[i].Start();
        }
    } //main
} //Test

class Slot
{
    private static Random randomGenerator = new Random();

    public static void SlotTest()
    {
        // Set different data in each thread's data slot.
        Thread.SetData(Thread.GetNamedDataSlot("Random"), 
            new Integer(randomGenerator.Next(1, 200)));

        // Write the data from each thread's data slot.
        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", 
            String.valueOf(AppDomain.GetCurrentThreadId()),
            Thread.GetData(Thread.GetNamedDataSlot("Random")).toString());

        // Allow other threads time to execute SetData to show
        // that a thread's data slot is unique to the thread.
        Thread.Sleep(1000);
        Console.WriteLine("Data in thread_{0}'s data slot is still: {1,3}",
            String.valueOf(AppDomain.GetCurrentThreadId()), 
            Thread.GetData(Thread.GetNamedDataSlot("Random")).toString());

        // Allow time for other threads to show their data,
        // then demonstrate that any code a thread executes
        // has access to the thread's named data slot.        
        Thread.Sleep(1000);

        Other o = new Other();

        o.ShowSlotData();
    } //SlotTest
} //Slot

public class Other
{
    public void ShowSlotData()
    {
        // This method has no access to the data in the Slot
        // class, but when executed by a thread it can obtain
        // the thread's data from a named slot.
        Console.WriteLine("Other code displays data in "
            + "thread_{0}'s data slot: {1,3}", 
            String.valueOf(AppDomain.GetCurrentThreadId()),
            Thread.GetData(Thread.GetNamedDataSlot("Random")).ToString());
    } //ShowSlotData
} //Other

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

Thread 类
Thread 成员
System.Threading 命名空间
GetData

其他资源

线程与线程处理
线程本地存储区和线程相关的静态字段