Search code examples
c#.netwpfcode-contracts

Code contracts checking thread affinity - good idea?


I'm trying to learn Code Contracts and get an idea of for what are they useful.

I have a WPF application, so a lot of code is bound to run exclusively on the UI thread. Quite a few utility classes expect to be called from the UI thread only.

Is it good idea so sprinkle these through my code? Why yes/not?

Contract.Requires(Thread.CurrentThread == Application.Current.Dispatcher.Thread);

Will the static checker be able to reliably check these?

Thanks for any input!


Solution

  • I think you are right to want to make these affinity checks. They are a great way to spot subtle bugs early but not something that can be checked statically using code contracts as mentions by Henk and decyclone.

    I have a static class called Ensure with a method Ensure.OnUiThread() that contains the exact same check as you mention. I mark this with [Conditional("DEBUG")] so as not to slow/bloat production code. Works nicely for me.