本文整理汇总了C#中System.Threading.Thread.AllocateDataSlot方法的典型用法代码示例。如果您正苦于以下问题:C# Thread.AllocateDataSlot方法的具体用法?C# Thread.AllocateDataSlot怎么用?C# Thread.AllocateDataSlot使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Thread
的用法示例。
在下文中一共展示了Thread.AllocateDataSlot方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ThreadStaticDemo
//引入命名空间
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 );
}
}
输出:
Data for managed thread 4: 4 Data for managed thread 5: 5 Data for managed thread 3: 3
示例2: Main
//引入命名空间
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;
static LocalDataStoreSlot localSlot;
static Slot()
{
randomGenerator = new Random();
localSlot = Thread.AllocateDataSlot();
}
public static void SlotTest()
{
// Set different data in each thread's data slot.
Thread.SetData(localSlot, 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(localSlot).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: {1,3}",
AppDomain.GetCurrentThreadId().ToString(),
Thread.GetData(localSlot).ToString());
}
}
示例3: Main
//引入命名空间
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;
public class MainClass
{
public static void Main()
{
LocalDataStoreSlot slot = Thread.AllocateDataSlot();
Thread.SetData(slot, 63);
int slotValue1 = (int)Thread.GetData(slot);
Console.WriteLine(slotValue1);
}
}