Reputation: 2616
i want to create singleton that has its own thread, and executes every method (lets assume this is database, and every add/modify action need to be called from the same thread), that thread can be created inside constructor, also i want that every method from that singleton will execute on this specific thread.
From what i understand, the new System.Threading.Thread.Thread() gives me ability to start thread, but after start, i cannot freely ququee next work to it. How to queue new work to that thread? This should work like myThread.Queue(()=> doWork()); but i dont see api like that.
Upvotes: 0
Views: 1509
Reputation: 886
The below simplified code shows how you can do this. TryTake will block indefinitely (or unitl collection.CompleteAdding()
is called, although there are overloads that accept a timeout value.
var collection = new BlockingCollection<Action>();
new Thread(() =>
{
while (collection.TryTake(out Action a, -1))
{
a.Invoke();
}
}
}).Start();
Upvotes: 3