From: UFO on 14 May 2010 06:20
i would like to know how to use a similar feature that exist on Java, on my
basically , the ThreadLocal allows you to decare&use a variable to be set
per thread, without the need to assign it from outside the thread itself.it
means that whoever uses the code doesn't even know that each thread he
creates , when it uses the class, it gets a new variable just for this thread.
for example, if i want to have a threadID , so that each new thread will
have a new number (from 0 , ascending) , i could use the next code on Java:
// Assigns unique contiguous ids to threads.
public class ThreadID
// The next thread ID to be assigned
private static AtomicInteger nextID =new AtomicInteger(0);
// My thread-local ID.
private static ThreadLocalID threadID =new ThreadLocalID();
// return unique ID for this thread
public static int get()
// Reset this thread's ID.the parameter is the index new ID
public static void set(int index)
// Assign new IDs from zero.
public static void reset()
public static int getNumberOfRegisteredThreads()
private static class ThreadLocalID extends ThreadLocal<Integer>
protected Integer initialValue()
so,for the first thread that uses this class by calling the 'get' function,
it will always (for all the next times that it calls this function) return 0.
for the second thread, it will always return 1 , and so on...
From: Alberto Poblacion on 14 May 2010 07:29
"UFO" <UFO(a)discussions.microsoft.com> wrote in message
> i would like to know how to use a similar feature that exist on Java, on
> C# program.
> basically , the ThreadLocal allows you to decare&use a variable to be set
> per thread, without the need to assign it from outside the thread itself.
You can apply a ThreadStaticAttribute to a static variable:
static int value;
From: UFO on 14 May 2010 17:25
to which variable ? the atomicInteger? if so,what about having a variable per
thread? if not, why should it be static?
can you please give me an example? maybe a way to do the same as what i've
it's just that i've searched the internet for any example of how to do such
a thing and i didn't find even one.
From: Tom Shelton on 14 May 2010 17:32
UFO explained :
> to which variable ? the atomicInteger? if so,what about having a variable per
> thread? if not, why should it be static?
> can you please give me an example? maybe a way to do the same as what i've
> it's just that i've searched the internet for any example of how to do such
> a thing and i didn't find even one.
It sounds as if your talking about TLS - thread local storage. Here is
an article that covers a bit about this on msdn:
It talks about thread relative static fields - which uses the
ThreadStaticAttribute and about dynamic tls using the various Thread
related tls functions (Thread.AllocateNamedDataSlot, etc).
From: UFO on 15 May 2010 18:47
again, please give me a code example. it's a too important feature that there
is no example of how to use it.