Is WPF Dispatcher the solution of multi threading problems?

后端 未结 3 1039
北海茫月
北海茫月 2020-12-07 15:03

I have a very bad feeling about using lock in my code but now the Dispatcher of WindowBase exists and I want to use it everywhere.

For example I use a multi thread s

3条回答
  •  情话喂你
    2020-12-07 15:44

    I'm going to necro the heck out of this, but this sounds like a bad idea. What you are saying is that you need a queue for your publisher to dump items on for its subscribers. A Dispatcher, at its core, is just a glorified queue, with a LOT of overhead around it. The overhead is specifically for protecting access to UI resources, which you aren't using. That suggests it's the wrong thing to use.

    The person who suggested a SynchronizationContext is on a good path. This accomplishes what you want (safely marshalling data to another thread), without tying you to a UI concept. You could write an extension method which marshals your event to the SynchronizationContext requested by each subscriber of the event (it is available by casting the Target of your subscribing Delegate to ISynchronizeInvoke. The result of that cast will allow you to know if it needs to be marhalled, and can do it automatically for you.

    Even better would be to just use a queue with appropriate locking semantics. The overhead of the lock is unlikely to be an issue, and if it is, your use of the Dispatcher would be far more destructive than a simple lock. In this case, simpler is better. They key would be to only keep the lock to add/remove an item from the queue. Your subscribers should perform whatever work they do outside of the lock.

提交回复
热议问题