I am reading DataModel-View-ViewModel pattern: 2
I don’t really understand the need to check if I am in the UI or Background thread. what if i skip the checks. Also, the code below …
[Conditional("Debug")]
protected void VerifyCalledOnUIThread()
{
Debug.Assert(Dispatcher.CurrentDispatcher == this.Dispatcher,
"Call must be made on UI thread.");
}
does not really do anything, eg. set values. So if I am not debugging will it do anything at all?
The reason for using the
Dispatcherand checking if you’re on the UI or background thread is because of WPF’s requirement that controls only be accessed on the thread they were created on. The reason for this is because the controls are not thread-safe. If you’re not doing multithreading (i.e. all of your code is on the main thread), then you don’t have to worry about this. WinForms has this same limitation.If you try to access a control from a different thread than the one it was created on, you’ll get an
InvalidOperationException.When compiling a release build,
Debug.Assert(and yourVerifyCalledOnUIThreadmethod) will not even appear in the code, so no, nothing will happen.