本文整理匯總了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);
}
}