|
| 1 | +using System; |
| 2 | +using System.Diagnostics; |
| 3 | +using System.Threading.Tasks; |
| 4 | + |
| 5 | +namespace SSR.Net.Models |
| 6 | +{ |
| 7 | + public enum ResultCallbackState |
| 8 | + { |
| 9 | + AwaitingCode, |
| 10 | + AwaitingResult, |
| 11 | + ResultAvailable |
| 12 | + } |
| 13 | + |
| 14 | + public class SSRNetResultCallback |
| 15 | + { |
| 16 | + private string _html { get; set; } |
| 17 | + private string _error { get; set; } |
| 18 | + private ResultCallbackState _state { get; set; } = ResultCallbackState.AwaitingCode; |
| 19 | + private string _executionId { get; set; } |
| 20 | + private object _lockObject { get; } = new object(); |
| 21 | + |
| 22 | + public void SetExecutionId(string executionId) |
| 23 | + { |
| 24 | + lock (_lockObject) { |
| 25 | + _html = null; |
| 26 | + _error = null; |
| 27 | + _executionId = executionId; |
| 28 | + _state = ResultCallbackState.AwaitingResult; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + public void SetHtml(string executionId, string html) => |
| 33 | + SetResult(executionId, html, null); |
| 34 | + |
| 35 | + public void SetError(string executionId, string error) => |
| 36 | + SetResult(executionId, null, error); |
| 37 | + |
| 38 | + private void SetResult(string executionId, string html, string error) |
| 39 | + { |
| 40 | + lock (_lockObject) { |
| 41 | + if (_state == ResultCallbackState.AwaitingResult && _executionId == executionId) { |
| 42 | + _html = html; |
| 43 | + _error = error; |
| 44 | + _state = ResultCallbackState.ResultAvailable; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + public async Task AwaitResult(int timeoutMs) |
| 50 | + { |
| 51 | + var sw = Stopwatch.StartNew(); |
| 52 | + while (_state != ResultCallbackState.ResultAvailable && sw.ElapsedMilliseconds < timeoutMs) |
| 53 | + await Task.Delay(1); |
| 54 | + lock (_lockObject) { |
| 55 | + if (_state != ResultCallbackState.ResultAvailable) { |
| 56 | + _state = ResultCallbackState.ResultAvailable; |
| 57 | + _error = $"Timeout after {timeoutMs}ms"; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + public bool HasHtml() => !(_html is null); |
| 63 | + |
| 64 | + public bool HasError() => !(_error is null); |
| 65 | + |
| 66 | + internal string RetrieveResult(string executionId) |
| 67 | + { |
| 68 | + lock (_lockObject) { |
| 69 | + if (_state != ResultCallbackState.ResultAvailable) |
| 70 | + throw new InvalidOperationException("Result not available."); |
| 71 | + if (_executionId != executionId) |
| 72 | + throw new InvalidOperationException("Execution ID didn't match."); |
| 73 | + var result = _html; |
| 74 | + _html = null; |
| 75 | + _error = null; |
| 76 | + _executionId = null; |
| 77 | + _state = ResultCallbackState.AwaitingCode; |
| 78 | + return result; |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments