コード例 #1
0
        /// <summary>
        /// Run basic example with option to cancel
        /// </summary>
        /// <param name="token">Valid CancellationToken</param>
        /// <returns></returns>
        public static async Task RunBasicExample(CancellationToken token)
        {
            await foreach (var item in RangeAsync(1, 90, 99, token))
            {
                if (token.IsCancellationRequested)
                {
                    token.ThrowIfCancellationRequested();
                }

                if (item > 100)
                {
                    throw new Exception("Well now");
                }
                OnIterateEvent?.Invoke(item);
            }
        }
コード例 #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="originalFile">File to copy</param>
        /// <param name="outputFile">File to copy too</param>
        /// <param name="delay">Milliseconds to delay to simulate a large file</param>
        /// <param name="token">cancellation token to permit cancelling this operation</param>
        /// <returns>Success</returns>
        /// <remarks>
        /// Exception handling is done at client level
        /// </remarks>
        public static async Task <bool> CopyFileTask(string originalFile, string outputFile, int delay, CancellationToken token)
        {
            int lineNumber = 0;

            using (var inputStream = File.OpenRead(originalFile))
            {
                using (var inputReader = new StreamReader(inputStream))
                {
                    using (var outputWriter = File.AppendText(outputFile))
                    {
                        var currentLine = await inputReader.ReadLineAsync();

                        await outputWriter.WriteLineAsync(currentLine);

                        if (delay > 0)
                        {
                            await Task.Delay(delay, token);
                        }

                        while (null != currentLine)
                        {
                            lineNumber += 1;
                            await outputWriter.WriteLineAsync(currentLine);

                            currentLine = await inputReader.ReadLineAsync();

                            OnIterateEvent?.Invoke(lineNumber);
                            if (token.IsCancellationRequested)
                            {
                                token.ThrowIfCancellationRequested();
                            }

                            if (delay > 0)
                            {
                                await Task.Delay(delay, token);
                            }
                        }
                    }
                }
            }

            return(true);
        }