> Is there an easy way for to create a Singleton so that for each thread
> a new instance is created?
>
> Threads share memory, so I'm not sure how to go about this one . . .
Use ThreadStatic:
using System;
using System.Threading;
class ThreadedSingleton
{
[ThreadStatic]
static ThreadedSingleton instance;
private ThreadedSingleton()
{
Console.WriteLine
("Creating instance in thread "+Thread.CurrentThread.Name);
}
public static ThreadedSingleton Instance
{
get
{
if (instance==null)
{
instance = new ThreadedSingleton();
}
return instance;
}
}
}
class Test
{
static void Main()
{
for (int i=0; i < 10; i++)
{
Thread t = new Thread(FetchSingleton);
t.Name = "Client thread "+i;
t.Start();
}
}
static void FetchSingleton()
{
for (int i=0; i < 5; i++)
{
ThreadedSingleton.Instance.ToString();
}
}
}

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
jehugaleahsa@gmail.com - 29 Feb 2008 16:46 GMT
> jehugalea...@gmail.com <jehugalea...@gmail.com> wrote:
> > Is there an easy way for to create a Singleton so that for each thread
[quoted text clipped - 57 lines]
> Jon Skeet - <sk...@pobox.com>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
> World class .NET training in the UK:http://iterativetraining.co.uk
Cool beans!