Skip to content

Instantly share code, notes, and snippets.

@westonal
Created May 27, 2016 13:04
Show Gist options
  • Select an option

  • Save westonal/261d7d61d54f3bd887666742df6f8383 to your computer and use it in GitHub Desktop.

Select an option

Save westonal/261d7d61d54f3bd887666742df6f8383 to your computer and use it in GitHub Desktop.
WPF ViewModelBase with async support
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