How to use AllocateNamedDataSlot method

X

xzzy

AllocateNamedDataSlot defined as:
Threads use a local store memory mechanism to store thread-specific data.
The common language runtime allocates a multi-slot data store array to each
process when it is created. The thread can allocate a data slot in the data
store, store and retrieve a data value in the slot, and free the slot for
reuse after the thread expires. Data slots are unique per thread. No other
thread (not even a child thread) can get that data.

I am confused, is a data slot created once for all threads, or for each
thread?



I want to create many threads with the code below.

The goal is to create threads, each new thread being able to read the value
of

myValue=Thread.GetNamedDataSlot("HID"); // the value of HID will be
different for each thread

via

myUID=Thread.GetNamedDataSlot("UID");

in AllJobs.ThisJob




++ Code to create a thread ++

Thread t = new Thread(new ThreadStart(AllJobs.ThisJob));
t.Name = "H" + yHeaderID + "D" + yDetailID;
t.IsBackground = true;

//the next line breaks
t.AllocateNamedDataSlot("UID");
//the previous line breaks

LocalDataStoreSlot ldssUID;
ldssUID=Thread.GetNamedDataSlot("UID");


//the next line doesn't make any sense
Thread.SetData(ldssUID, yUID);
//the previous line doesn't make any sense

t.Start();


++ End of code to create a thread ++


Thank you
 
N

Nicholas Paldino [.NET/C# MVP]

xzzy,

There really is no reason to use this in .NET. Rather, you should
create a static field in your class and adorn it with the ThreadStatic
attribute. It will make sure that each thread has a different value.

You should then wrap that field in a property which will check the
value, making sure it is initialized properly before you access it.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top