Running self suicide thread from event handler
I am very new to multi threading and c#, I have to solve this probelm: I have event handler which is fired pretty often (it must be done that way, because event handler calls are invoked from the dll) When handler method is invoked, I need to create and run one thread which will do some stuff and its processing can vary from few millisconds to few seconds, when finishes its work it kills itself. When it's finis开发者_StackOverflow中文版hed, evenhandler can create another thread. Meanwhile created thread is running, no other threads can be created and runned from eventhandler.
Many thanks for help.
This all sounds pretty complicated, and I don't have a good sense of what you're actually trying to do, but it sounds like this would be better handled with a single extra thread and a shared queue of work items. Your event handler would just add another work item to the queue, and the thread would pick items off the queue and process them one at a time.
.NET 4 makes this easy with the BlockingCollection<T>
type. Before .NET 4 it's still doable of course, but you'll need to find a third-party thread-safe producer/consumer queue or write one yourself.
Threads that kill themselves present problems. You have to synchronise with the main thread when the thread does kill itself.
It sounds to me as though you would be better off with a single dedicated thread that did the work. Use a blocking queue and implement the producer/consumer pattern. Rather than kill the thread when it has nothing to do, let it sit idle until more work arrives.
精彩评论