• c# 控制台应用程序


    此篇是对于控制台应用程序 | Microsoft Learn的实践,具体请参考原链接

    一 控制台读取文件

    1. namespace TeleprompterConsole;
    2. internal class Program
    3. {
    4. static void Main(string[] args)
    5. {
    6. Console.WriteLine("Hello World!");
    7. var lines = ReadFrom("sampleQuotes.txt");
    8. foreach (var line in lines)
    9. {
    10. Console.WriteLine(line);
    11. }
    12. }
    13. //读取文本文件,然后在控制台中显示全部文本
    14. //首先,让我们来添加文本文件。
    15. static IEnumerable<string> ReadFrom(string file)
    16. {
    17. string? line;
    18. using (var reader = File.OpenText(file))
    19. {
    20. while ((line = reader.ReadLine()) != null)
    21. {
    22. ///这是一种称为“iterator 方法”的特殊类型 C# 方法。 迭代器方法返回延迟计算的序列。
    23. ///也就是说,序列中的每一项是在使用序列的代码提出请求时生成。 迭代器方法包含一个或多个 yield return 语句。
    24. yield return line;
    25. }
    26. }
    27. }
    28. }

     在控制台输出的结构如下:

    1. Hello World!
    2. hello Lianhua
    3. nihaoya
    4. i am glad to meet you
    5. hahahh
    6. huhufi

    二 添加延迟和设置输出格式

    你可以看到一个单词一个单词的写入过程

    1. namespace TeleprompterConsole;
    2. internal class Program
    3. {
    4. static void Main(string[] args)
    5. {
    6. Console.WriteLine("Hello World!");
    7. var lines = ReadFrom("sampleQuotes.txt");
    8. //修改对文件行的使用方式,并在写入每个字词后添加延迟。
    9. foreach (var line in lines)
    10. {
    11. Console.Write(line);
    12. if (!string.IsNullOrWhiteSpace(line))
    13. {
    14. var pause = Task.Delay(200);
    15. // Synchronously waiting on a task is an
    16. // anti-pattern. This will get fixed in later
    17. // steps.
    18. pause.Wait();
    19. }
    20. }
    21. }
    22. //读取文本文件,然后在控制台中显示全部文本
    23. //首先,让我们来添加文本文件。
    24. //将迭代器方法更新为返回单个字词,而不是整行文本。
    25. static IEnumerable<string> ReadFrom(string file)
    26. {
    27. string? line;
    28. using (var reader = File.OpenText(file))
    29. {
    30. while ((line = reader.ReadLine()) != null)
    31. {
    32. var words = line.Split(' ');
    33. var lineLength = 0;
    34. foreach (var word in words)
    35. {
    36. yield return word + " ";
    37. lineLength += word.Length + 1;
    38. if (lineLength > 70)
    39. {
    40. yield return Environment.NewLine;
    41. lineLength = 0;
    42. }
    43. }
    44. yield return Environment.NewLine;
    45. }
    46. }
    47. }
    48. }

    三 异步任务

    在这里的代码上,有两个任务(GetInput 和 ShowTeleprompter),并管理这两项任务之间共享的数据

    1. namespace TeleprompterConsole;
    2. using static System.Math;
    3. internal class TelePrompterConfig
    4. {
    5. public int DelayInMilliseconds { get; private set; } = 200;
    6. public void UpdateDelay(int increment) // negative to speed up
    7. {
    8. var newDelay = Min(DelayInMilliseconds + increment, 1000);
    9. newDelay = Max(newDelay, 20);
    10. DelayInMilliseconds = newDelay;
    11. }
    12. public bool Done { get; private set; }
    13. public void SetDone()
    14. {
    15. Done = true;
    16. }
    17. }

     

    1. namespace TeleprompterConsole;
    2. internal class Program
    3. {
    4. static async Task Main(string[] args)
    5. {
    6. Console.WriteLine("Hello World!");
    7. await RunTeleprompter();
    8. }
    9. //Task 对象由编译器在你使用 await 运算符时生成的代码进行创建。
    10. //可以想象,此方法在到达 await 时返回。 返回的 Task 指示工作未完成。 在等待的任务完成时,此方法继续执行。
    11. //执行完后,返回的 Task 会指示已完成。 调用代码可以通过监视返回的 Task 来确定完成时间。
    12. private static async Task RunTeleprompter()
    13. {
    14. var config = new TelePrompterConfig();
    15. var displayTask = ShowTeleprompter(config);
    16. var speedTask = GetInput(config);
    17. await Task.WhenAny(displayTask, speedTask);
    18. }
    19. //读取文本文件,然后在控制台中显示全部文本
    20. //首先,让我们来添加文本文件。
    21. //将迭代器方法更新为返回单个字词,而不是整行文本。
    22. static IEnumerable<string> ReadFrom(string file)
    23. {
    24. string? line;
    25. using (var reader = File.OpenText(file))
    26. {
    27. while ((line = reader.ReadLine()) != null)
    28. {
    29. var words = line.Split(' ');
    30. var lineLength = 0;
    31. foreach (var word in words)
    32. {
    33. yield return word + " ";
    34. lineLength += word.Length + 1;
    35. if (lineLength > 70)
    36. {
    37. yield return Environment.NewLine;
    38. lineLength = 0;
    39. }
    40. }
    41. yield return Environment.NewLine;
    42. }
    43. }
    44. }
    45. private static async Task ShowTeleprompter(TelePrompterConfig config)
    46. {
    47. var words = ReadFrom("sampleQuotes.txt");
    48. foreach (var word in words)
    49. {
    50. Console.Write(word);
    51. if (!string.IsNullOrWhiteSpace(word))
    52. {
    53. await Task.Delay(config.DelayInMilliseconds);
    54. }
    55. }
    56. config.SetDone();
    57. }
    58. private static async Task GetInput(TelePrompterConfig config)
    59. {
    60. Action work = () =>
    61. {
    62. do
    63. {
    64. var key = Console.ReadKey(true);
    65. if (key.KeyChar == '>')
    66. config.UpdateDelay(-10);
    67. else if (key.KeyChar == '<')
    68. config.UpdateDelay(10);
    69. else if (key.KeyChar == 'X' || key.KeyChar == 'x')
    70. config.SetDone();
    71. } while (!config.Done);
    72. };
    73. await Task.Run(work);
    74. }
    75. }

    没有按键盘的正常流程的结果:

    1. Hello World!
    2. hello Lianhua
    3. nihaoya
    4. i am glad to meet you
    5. hahahh
    6. Once when I was six years old I saw a magnificent picture in a book, called
    7. True Stories from Nature, about the primeval forest. It was a picture of
    8. a boa constrictor in the act of swallowing an animal. Here is a copy of
    9. the drawing.
    10. In the book it said, "Boa constrictors swallow their prey whole, without
    11. chewing it. After that they are not able to move, and they sleep through
    12. the six months that they need for digestion."
    13. I pondered deeply, then, over the adventures of the jungle. And after some
    14. work with a colored pencil I succeeded in making my first drawing. My Drawing
    15. Number One. It looked like this:
    16. I showed my masterpiece to the grown-ups, and asked them whether the drawing
    17. frightened them.
    18. But they answered, "Frighten? Why should anyone be frightened by a hat?"
    19. My drawing was not a picture of a hat. It was a picture of a boa constrictor
    20. digesting an elephant. But since the grown-ups were not able to understand
    21. it, I made another drawing: I drew the inside of the boa constrictor, so
    22. that the grown-ups could see it clearly. They always need to have things
    23. explained. My Drawing Number Two looked like this:
    24. C:\...\ConsolePractice.exe (process 14244) exited with code 0.

     下面是我在运行的时候使用键盘,按了x后的结果:

    1. Hello World!
    2. hello Lianhua
    3. nihaoya
    4. i am glad to meet you
    5. hahahh
    6. Once when I was six years old I saw a magnificent picture in a book, called
    7. True Stories from Nature, about the primeval forest. It was a
    8. C:\...\net6.0\ConsolePractice.exe (process 18896) exited with code 0.
    9. Press any key to close this window . . .

  • 相关阅读:
    【Java入门】交换数组中两个元素的位置
    软考 系统架构设计师 简明教程 | 系统设计
    微信小程序导航退回及跳转 传参(navigateBack,navigateTo)
    Redis设计与实现-数据结构(建设进度17%)
    PyTorch:计算图
    SpringBoot--网上商城项目(前端搭建、首页、用户登录、盐加密、登录令牌管理)
    Linux I2C驱动入门之读取bmp280传感器的ID寄存器的值
    如何设计一个C语言面向结构体的内存数据库
    固高机器人控制器开发笔记
    Halcon File相关算子(一)
  • 原文地址:https://blog.csdn.net/hellolianhua/article/details/127900071