.NET: How do I invoke a delegate on a specific thread? (ISynchronizeInvoke, Dispatcher, AsyncOperation, SynchronizationContext, etc.)

后端 未结 2 1430
说谎
说谎 2021-02-01 09:31

Note first of all that this question is not tagged winforms or wpf or anything else GUI-specific. This is intentional, as you will see shortly.

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 10:19

    If you want to support calling a delegate on a thread which doesn't otherwise have a message loop, you have to implement your own, basically.

    There's nothing particularly magic about a message loop: it's just like a consumer in a normal producer/consumer pattern. It keeps a queue of things to do (typically events to react to), and it goes through the queue acting accordingly. When there's nothing left to do, it waits until something is placed in the queue.

    To put it another way: you can think of a thread with a message loop as a single-thread thread pool.

    You can implement this yourself easily enough, including in a console app. Just remember that if the thread is looping round the work queue, it can't be doing something else as well - whereas typically the main thread of execution in a console app is meant to perform a sequence of tasks and then finish.

    If you're using .NET 4, it's very easy to implement a producer/consumer queue using the BlockingCollection class.

提交回复
热议问题