public async Task LoadAsync() { //wait for the semaphore await _semaphore.WaitAsync(); try { //state management if (State == SnapshotState.Loading) { return; } State = SnapshotState.Loading; //load data from the factory Data = new SnapshotData <TData>(await _dataFactory()); State = SnapshotState.Loaded; //release the semaphore _semaphore.Release(); } catch { //set state State = SnapshotState.Failed; //release the semaphore _semaphore.Release(); //leak exception to caller throw; } }
public Snapshot(Func <Task <TData> > dataFactory, TData initialData) { _dataFactory = dataFactory; _semaphore = new SemaphoreSlim(1); State = SnapshotState.Empty; Data = new SnapshotData <TData>(initialData); }