I have a Queue of items I want to process in a thread, and any instance of a class can add items to the Queue to be processed.
My idea for doing this is to have a static Thread in the class that processes the items, the only problem is that I don’t know where to start this thread, since I can’t start it in its initialization.
Is there a way I can start a static thread? Or should I be changing the architecture completely?
You can start it in the static constructor for the class:
You could also start it in the regular constructor of the class using a typical singleton approach.
Or you could use the new .NET 4
Lazy<T>approach to instantiating and starting it.BUT it’s generally not a good practice to do work in class constructors. A better approach would be to ensure the thread exists only when someone calls, say
Execute()on an instance of the class. Within theExecutemethod you can useLazy<T>or a singleton approach to creating and starting the single thread instance that will process it.Purists will point out that actually you probably don’t want to do this at all and that a Factory approach may be better for creating instances of your class and that you should separate the concerns between your class and the worker that processes it.
Other would suggest that you don’t need a thread here at all, just use .NET4
Tasks and queue the items up for execution using the framework provided queue/execute methods.