There is the following code

public class MyWindow: Window { private delegate void SomeDelegate(); private void SomeMethod() { SomeControl.DoAnything(); } private void SomeMethodAsync() { var d = new SomeDelegate(SomeMethod); d.BeginInvoke(null, null); } } 

By itself, I can not access the control from another thread. therefore

 SomeControl.DoAnything(); 

need to wrap in

 Dispatcher.BeginInvoke(new ThreadStart(delegate { SomeControl.DoAnything(); })); 

But this is redundant if I call SomeMethod() directly. What is better to do in this case?

  • one
    Do you use any MVVM framework? - ixSci
  • @ixSci, I do not use - iRumba

1 answer 1

The simplest thing to do is:

 if(Application.Current.Dispatcher.CheckAccess()) SomeControl.DoAnything(); else Application.Current.Dispatcher.BeginInvoke(() => SomeControl.DoAnything();); 

But this solution cannot be tested in unit tests, therefore, the best solution is to memorize the UI Dispatcher in the ViewModel, and further use of this stored argument, instead of a global reference to Application . If you use any MVVM framework, there surely is this functionality out of the box.

  • Considering that the view method itself is clearly here - can the dispatcher of the view itself be used? SomeControl.Dispatcher vsmysle. Or is it still not an option in tests? =) - Monk
  • @Monk, I rather answer the question in general, so it will be more useful. If we talk specifically about the code from the question, then if someone calls the window method from a non-UI stream, then it already smacks, and strongly. - ixSci
  • @ixSci, what there, say, this code smacks? :) Tell me in detail, please. The answer to the question “What is better to do in this case?” May well begin with the lines “delete your code and write this” :) Therefore, please complete the answer and write how you work with streams. - iRumba
  • @iRumba, the point here is not in the streams, but in the fact that, apparently, you had some kind of logic in View that should not be there. A classic GUI application should obey a simple model: Model-Mediator-Representation, for WPF this is MVVM, I will not paint all this in detail, people write huge articles and books about it. In addition - one question, one answer. You asked a very specific question to which I gave a very specific answer. If you have a design question, then ask it separately, please. - ixSci
  • And yes. The code doesn't just smack, the code really stinks. The code is not written by me. I just change something in it. There is not even a hint of MVVM in it, but if you put the code under this pattern, it will take a lot of time. This is not part of my task, so ... Operating on what I have - iRumba