Actually I don't think this should be a problem. If you are using a singleton pattern you are probably calling a shared method that initializes your object. Even though the object is created on a certain thread this should not prevent it from being accessed from others (unless it's some UI control that is thread bound, but in that case initializing it from the main thread wouldn't solve your 'problem'). As far as I know your object is created on a specific thread, called from specific threads, but stored in the same memory that is thread independant.
Consider the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Threading.Tasks.Task.Factory.StartNew(() => SetSingletonText());
System.Threading.Thread.Sleep(2000);
PrintSingletonText();
SetSingletonText();
PrintSingletonText();
System.Threading.Tasks.Task.Factory.StartNew(() => PrintSingletonText());
Console.ReadKey();
}
static void SetSingletonText()
{
Singleton.GetInstance().SomeText =
String.Format("Hello from thread {0}!", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
}
static void PrintSingletonText()
{
Console.WriteLine(String.Format("Written on Thread {0}: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, Singleton.GetInstance().SomeText));
}
}
class Singleton
{
private static Singleton _singleton;
public string SomeText { get; set; }
public static Singleton GetInstance()
{
if (_singleton == null)
{
_singleton = new Singleton();
}
return _singleton;
}
}
}
Run it and read the results.
As you can see I can get and set
SomeText
from any thread. You DO have to make sure your class is thread safe though.
If, for example, you have an integer variable with value 1 and multiply it by 2 from one thread and then add 3 from another thread the order in which the threads access the variable will affect your outcome! If you FIRST multiply 1 by 2 (which is 2) and then add 3 you'll have 5. If you first add 3 and then multiply by 2 you'll have 8. This is also known as a
race condition[
^].
If you need to synchronize to your main thread from another thread there are also other methods available, depending on how you are starting your thread.
Using a class or method in a multithreaded environment, but only making it work if it was created on some specific thread sounds like a bad idea. Your co-workers may not know your intentions or will even call the method that initializes your object on a worker thread!
For further reading see:
Threading Tutorial (C#)[
^]
Thread Synchronization (C# and Visual Basic)[
^]
Of course you could still simply call your method on the main thread and hope it will stay that way. It's your call :)