Example #1
0
        private async IAsyncEnumerable <string> GetOutput(Guid id, OutputType type, [EnumeratorCancellation] CancellationToken cancellationToken)
        {
            var output = _outputService.GetOutput(id);

            if (output == null)
            {
                string dbOutput = await this.GetDbOutput(id, type, cancellationToken);

                yield return(dbOutput);

                yield break;
            }

            var  resetEvent = output.Subscribe();
            var  sent       = string.Empty;
            bool done       = false;

            do
            {
                if (output.Complete)
                {
                    done = true;
                }

                var newContent = output.Content.Substring(sent.Length);

                yield return(newContent);

                sent += newContent;

                if (!done)
                {
                    try
                    {
                        await resetEvent.WaitAsync(cancellationToken);
                    }
                    catch (TaskCanceledException)
                    {
                        done = true;
                    }
                }
            }while (!done);

            output.Unsubscribe(resetEvent);
        }