Last active
January 23, 2019 11:00
-
-
Save Ilchert/5c926bdc35a8cbb5f24043743206a7b7 to your computer and use it in GitHub Desktop.
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
public class CompositeCompletion | |
{ | |
private int _lockCount; | |
private bool _isTaskCreated = false; | |
private Action _completeAction; | |
private readonly object _syncObject = new object(); | |
public IObservable<T> Add<T>(IObservable<T> observable) | |
{ | |
lock (_syncObject) | |
{ | |
if (_isTaskCreated) | |
throw new InvalidOperationException($"Can not add new completion after task creation. See {nameof(CreateTask)}."); | |
_lockCount++; | |
} | |
return observable.Finally(() => | |
{ | |
lock (_syncObject) | |
{ | |
_lockCount--; | |
if (_lockCount == 0) | |
_completeAction?.Invoke(); | |
} | |
}); | |
} | |
public Task CreateTask() | |
{ | |
lock (_syncObject) | |
{ | |
if (_lockCount == 0) | |
return Task.CompletedTask; | |
var tcs = new TaskCompletionSource<int>(); | |
_completeAction = () => tcs.SetResult(1); | |
_isTaskCreated = true; | |
return tcs.Task; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment