本文整理汇总了C#中System.Threading.Thread.SetData方法的典型用法代码示例。如果您正苦于以下问题:C# Thread.SetData方法的具体用法?C# Thread.SetData怎么用?C# Thread.SetData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Thread
的用法示例。
在下文中一共展示了Thread.SetData方法的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
{
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);
}
}
}
示例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);
}
}