Last active
October 1, 2016 13:56
-
-
Save i3arnon/0fa802faf7f93493d0142771797c47e0 to your computer and use it in GitHub Desktop.
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
public class Poller<TData> | |
{ | |
private readonly Func<Task<TData>> _func; | |
private Task<TData> _task; | |
private int _hasData; | |
// Returns default values before first poll. | |
public TData Data { get; private set; } | |
public bool HasData => _hasData == 1; | |
public Poller(Func<Task<TData>> func) | |
{ | |
_func = async () => | |
{ | |
var result = await func(); | |
Data = result; | |
return result; | |
}; | |
} | |
public Task<TData> PollAsync(bool refresh = false) | |
{ | |
// First call polls data. | |
if (_hasData == 0 && | |
Interlocked.CompareExchange(ref _hasData, 1, 0) == 0) | |
{ | |
_task = _func(); | |
} | |
// Force polls and replaces data when done. | |
else if (refresh) | |
{ | |
return _func().ContinueWith(_ => | |
{ | |
_task = _; | |
return _.GetAwaiter().GetResult(); | |
}, | |
CancellationToken.None, | |
TaskContinuationOptions.ExecuteSynchronously, | |
TaskScheduler.Default); | |
} | |
return _task; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment