Created
May 27, 2016 13:04
-
-
Save westonal/261d7d61d54f3bd887666742df6f8383 to your computer and use it in GitHub Desktop.
WPF ViewModelBase with async support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.ComponentModel; | |
| using System.Runtime.CompilerServices; | |
| using System.Threading; | |
| using System.Threading.Tasks; | |
| namespace WPF | |
| { | |
| public abstract class ViewModelBase : INotifyPropertyChanged | |
| { | |
| private readonly SynchronizationContext _context = SynchronizationContext.Current; | |
| public event PropertyChangedEventHandler PropertyChanged; | |
| //[NotifyPropertyChangedInvocator] resharper annotation | |
| protected void OnPropertyChanged([CallerMemberName] string propertyName = null) | |
| { | |
| PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); | |
| } | |
| protected void DoAsync<TResult>(Func<Task<TResult>> asyncTask, Action<TResult> onUiWithResult) | |
| { | |
| Task.Factory.StartNew(async () => | |
| { | |
| TResult data = await asyncTask(); | |
| DoOnUi(() => onUiWithResult(data)); | |
| }); | |
| } | |
| protected void DoOnUi(Action func) | |
| { | |
| _context.Post(o => func(), null); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment