Singleton - One Per Thread

  • Thread starter Thread starter jehugaleahsa
  • Start date Start date
J

jehugaleahsa

Hello:

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 . . .

Thanks,
Travis
 
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();
}
}
}
 
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();
        }
    }

}

Cool beans!
 

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

Back
Top