|
I need a thread to invoke any delegate that I send to it.
What is the accepted pattern for having a .NET thread process messages?
Should I:
1. Create a hidden Form and override the WndProc function?
2. Use a Background Worker? (The problem with the Background Worker is that you can't send it a message if it's already busy.)
3. Use a loop with an AutoResetEvent to wait for new messages?
4. Something else?
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
Richard Andrew x64 wrote: 1. Create a hidden Form and override the WndProc function?
No, that thread is meant to handle the UI. It'll hang (along with the UI) if it's already busy, as stated in point 2.
Richard Andrew x64 wrote: 2. Use a Background Worker? (The problem with the Background Worker is that you can't send it a message if it's already busy.)
One can only process one thing at a time. You could consider queuing the request, or to use multiple threads.
Richard Andrew x64 wrote: 3. Use a loop with an AutoResetEvent to wait for new messages?
Loop within a Thread[^] from the ThreadPool . Easiest would be to check for new items at the begin of the loop
|
|
|
|
|
That depends on what you really need.
In my case I created a class (ActionRunner... and later a RunnableRunner). I use a Thread from my own pool of threads. It waits for a new Action (using a ManagedAutoResetEvent) and uses a Queue to effectively queue the Actions.
So, while there are items in the queue they are executed. When there are no more, an wait is done. My own ActionRunner is disposable, but that's to guarantee that I free the thread at the right moment. I consider it the best solution as it does not creates an unnecessary window and because the messages are real .Net actions (and not some number that must be processed by a switch).
|
|
|
|
|
Depends on what you need.
If you want to respond to messages and spawn parallel tasks that don't depend on each other, then check out the Task Parallel Library, or BackgroundWorker.
If you want a queue of messages that a thread works through one by one, then I'd implement a background thread class (i.e. wrap a Thread) with a Queue<Message>, and do the queue pumping myself.
|
|
|
|