Last active
June 7, 2018 13:03
-
-
Save AlbertoDePena/42312035c1d19ee9190046e0c7b9a0cb to your computer and use it in GitHub Desktop.
Load data / lookups within contructor.
This file contains 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.Threading.Tasks; | |
namespace MyNameSpace | |
{ | |
public sealed class NotifiableTask<TResult> : INotifyPropertyChanged | |
{ | |
public NotifiableTask(Task<TResult> task) | |
{ | |
Task = task; | |
if (!task.IsCompleted) | |
{ | |
var _ = ExecuteAsync(task); | |
} | |
} | |
public event PropertyChangedEventHandler PropertyChanged; | |
public string ErrorMessage => InnerException?.Message; | |
public string IsCompletedPropertyName => nameof(IsCompleted); | |
public bool IsNotCompleted => !Task.IsCompleted; | |
public bool IsSuccessfullyCompleted => Task.Status == TaskStatus.RanToCompletion; | |
public Task<TResult> Task { get; } | |
public AggregateException Exception => Task.Exception; | |
public Exception InnerException => Exception?.InnerException; | |
public bool IsCanceled => Task.IsCanceled; | |
public bool IsCompleted => Task.IsCompleted; | |
public bool IsFaulted => Task.IsFaulted; | |
public TResult Result => (Task.Status == TaskStatus.RanToCompletion) ? Task.Result : default(TResult); | |
public TaskStatus Status => Task.Status; | |
private async Task ExecuteAsync(Task task) | |
{ | |
try | |
{ | |
await task; | |
} | |
catch | |
{ | |
// Do not propagate exception directly back to main UI loop. | |
} | |
var propertyChanged = PropertyChanged; | |
if (propertyChanged == null) return; | |
propertyChanged(this, new PropertyChangedEventArgs(nameof(Status))); | |
propertyChanged(this, new PropertyChangedEventArgs(nameof(IsCompleted))); | |
propertyChanged(this, new PropertyChangedEventArgs(nameof(IsNotCompleted))); | |
if (task.IsCanceled) | |
{ | |
propertyChanged(this, new PropertyChangedEventArgs(nameof(IsCanceled))); | |
return; | |
} | |
if (task.IsFaulted) | |
{ | |
propertyChanged(this, new PropertyChangedEventArgs(nameof(IsFaulted))); | |
propertyChanged(this, new PropertyChangedEventArgs(nameof(Exception))); | |
propertyChanged(this, new PropertyChangedEventArgs(nameof(InnerException))); | |
propertyChanged(this, new PropertyChangedEventArgs(nameof(ErrorMessage))); | |
return; | |
} | |
propertyChanged(this, new PropertyChangedEventArgs(nameof(IsSuccessfullyCompleted))); | |
propertyChanged(this, new PropertyChangedEventArgs(nameof(Result))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment