简体   繁体   中英

How to prevent UI thread from entering model in WPF MVVM application?

I'd like to establish a rule in my application architecture that no code in model objects should execute on the UI thread. The question is, how do I enforce this?

In C# using async/await, which thread something is executed on is generally determined by the caller. So if a user clicks a button, the event handler is running on the UI thread and it calls into my view model. In the view model, I want the developer to do something like call Task.Run() when calling methods on the model. But this is easy to forget. There are also non-obvious loopholes like raising an event that has been wired up to a listener that is a model object. Ideally, when a developer makes this kind of programming mistake, an exception would be thrown as soon as the UI thread tries to execute the method on the model. What I'd really like is a way to mark the assembly containing the model classes in a way that causes any method in it to throw an exception as soon as it is entered by the UI thread. The closest I've been able to come up with is to add a debug assertion at the beginning of every method to check the thread and fail if it is the UI thread. However, that litters the code with ugly checks and is another thing that can be forgotten.

EDIT: To clarify, I don't need to make it impossible . I just need to make it easy to do correctly and identify when it is done incorrectly. To put it into the pit of success.

The question is, how do I enforce this?

You do not. There is no way to enforce a logical separation of concerns via simple language rules.

The best way you can do is write an analyzer for this point that shows a warning in Visual Studio. BUT... have fun with that, I see this as an overly complex task not worth the time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM