how do you implement Async Operations in C# and MVVM?

后端 未结 3 1117
甜味超标
甜味超标 2021-02-04 14:28

hi what is the easiest way to implement asynch operations on WPF and MVVM, lets say if user if user hits enter when on a field i want to launch a command and then return back wh

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 14:54

    Rob Eisenberg showed a really clean implementation of running async operations in MVVM during his MIX10 talk. He has posted the source code on his blog.

    The basic idea is that you implement the command as returning an IEnumerable and use the yield keyword to return the results. Here is a snippet of code from his talk, which does a search as a background task:

        public IEnumerable ExecuteSearch()
        {
            var search = new SearchGames
            {
                SearchText = SearchText
            }.AsResult();
    
            yield return Show.Busy();
            yield return search;
    
            var resultCount = search.Response.Count();
    
            if (resultCount == 0)
                SearchResults = _noResults.WithTitle(SearchText);
            else if (resultCount == 1 && search.Response.First().Title == SearchText)
            {
                var getGame = new GetGame
                {
                    Id = search.Response.First().Id
                }.AsResult();
    
                yield return getGame;
                yield return Show.Screen()
                    .Configured(x => x.WithGame(getGame.Response));
            }
            else SearchResults = _results.With(search.Response);
    
            yield return Show.NotBusy();
        }
    

    Hope that helps.

提交回复
热议问题