Note that there are some explanatory texts on larger screens.

plurals
  1. POAsynchrony with TAP (async/await) in WPF MVVM
    primarykey
    data
    text
    <p>I am looking for a best practice to the following setup.</p> <p>A View is data bound to ViewModel (through WPF). ViewModel updates View via INotifyPropertyChanged. Model updates ViewModel via events. The Model knows about stuff from the outside-world, like how to get stuff from the internet via WebClient, and how to retrieve data from a database.</p> <p>Getting and sending stuff to the outside-world should be done asynchronously in order for the UI (and by extension, the user) not to suffer from waiting on the outside-world.</p> <p>What would be the best practice way to go about this? </p> <p><strong>1.</strong> The ViewModel should be responsible for calling model methods asynchronously.<br> This would have the advantage of being able to write stuff like</p> <pre><code>GetWebPage(string url) { var result = await Model.GetWebPageAsync(url); Url = result.Url; } </code></pre> <p>in the ViewModel where <code>Url</code> is a ViewModel property with INotifyPropertyChanged to update the View. Or even </p> <pre><code>GetWebPage(string url) { var result = await Model.GetWebPageAsync(url); _view.Url = result.Url; } </code></pre> <p>where we can avoid the INotifyPropertyChanged all together. Which of these ways do you prefer?</p> <p>However, it might be more sensible to have the Model itself do the asynchronous work. We might want to be able to use the Model without the View and ViewModel, while still having it work asynchronously. Another argument is that, who knows better that the Model what stuff is best handled asynchronously.</p> <p><strong>2.</strong> The Model handles all the asynchronous stuff by itself. The ViewModel code becomes more like</p> <pre><code>GetWebPage(string url) { Model.GetWebPage(url); } </code></pre> <p>and in the Model</p> <pre><code>GetWebPage(string url) { var result = await Model.GetWebPageAsync(url); if (UrlChanged != null); UrlChanged(this, new UrlChangedEventArgs(url)); } </code></pre> <p>that the ViewModel can subscribe to, and update the View accordingly.</p> <p>Which of the ways do you think is the best practice?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload