c# 控制台应用程序

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

一 控制台读取文件

namespace TeleprompterConsole;

internal class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        var lines = ReadFrom("sampleQuotes.txt");
        foreach (var line in lines)
        {
            Console.WriteLine(line);
        }
    }


    //读取文本文件,然后在控制台中显示全部文本

    //首先,让我们来添加文本文件。
    static IEnumerable<string> ReadFrom(string file)
    {
        string? line;
        using (var reader = File.OpenText(file))
        {
            while ((line = reader.ReadLine()) != null)
            {
                ///这是一种称为“iterator 方法”的特殊类型 C# 方法。 迭代器方法返回延迟计算的序列。 
                ///也就是说,序列中的每一项是在使用序列的代码提出请求时生成。 迭代器方法包含一个或多个 yield return 语句。
                yield return line;
                
            }
        }
    }
}

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

Hello World!
hello Lianhua
nihaoya
i am glad to meet you
hahahh


huhufi

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

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

namespace TeleprompterConsole;

internal class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        var lines = ReadFrom("sampleQuotes.txt");
            //修改对文件行的使用方式,并在写入每个字词后添加延迟。
        foreach (var line in lines)
        {
            Console.Write(line);
            if (!string.IsNullOrWhiteSpace(line))
            {
                var pause = Task.Delay(200);
                // Synchronously waiting on a task is an
                // anti-pattern. This will get fixed in later
                // steps.
                pause.Wait();
            }
        }
    }

    //读取文本文件,然后在控制台中显示全部文本

    //首先,让我们来添加文本文件。
    //将迭代器方法更新为返回单个字词,而不是整行文本。 
    static IEnumerable<string> ReadFrom(string file)
    {
        string? line;
        using (var reader = File.OpenText(file))
        {
            while ((line = reader.ReadLine()) != null)
            {
                var words = line.Split(' ');
                var lineLength = 0;
                foreach (var word in words)
                {
                    yield return word + " ";
                    lineLength += word.Length + 1;
                    if (lineLength > 70)
                    {
                        yield return Environment.NewLine;
                        lineLength = 0;
                    }
                }
                yield return Environment.NewLine;
            }
        }
    }
}

三 异步任务

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

namespace TeleprompterConsole;

using static System.Math;
internal class TelePrompterConfig
{
    public int DelayInMilliseconds { get; private set; } = 200;
    public void UpdateDelay(int increment) // negative to speed up
    {
        var newDelay = Min(DelayInMilliseconds + increment, 1000);
        newDelay = Max(newDelay, 20);
        DelayInMilliseconds = newDelay;
    }

    public bool Done { get; private set; }
    public void SetDone()
    {
        Done = true;
    }
}

 

namespace TeleprompterConsole;

internal class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        await RunTeleprompter();
    }
    //Task 对象由编译器在你使用 await 运算符时生成的代码进行创建。
    //可以想象,此方法在到达 await 时返回。 返回的 Task 指示工作未完成。 在等待的任务完成时,此方法继续执行。
    //执行完后,返回的 Task 会指示已完成。 调用代码可以通过监视返回的 Task 来确定完成时间。

    private static async Task RunTeleprompter()
    {
        var config = new TelePrompterConfig();
        var displayTask = ShowTeleprompter(config);
        var speedTask = GetInput(config);
        await Task.WhenAny(displayTask, speedTask);
    }

    //读取文本文件,然后在控制台中显示全部文本
    //首先,让我们来添加文本文件。
    //将迭代器方法更新为返回单个字词,而不是整行文本。 
    static IEnumerable<string> ReadFrom(string file)
    {
        string? line;
        using (var reader = File.OpenText(file))
        {
            while ((line = reader.ReadLine()) != null)
            {
                var words = line.Split(' ');
                var lineLength = 0;
                foreach (var word in words)
                {
                    yield return word + " ";
                    lineLength += word.Length + 1;
                    if (lineLength > 70)
                    {
                        yield return Environment.NewLine;
                        lineLength = 0;
                    }
                }
                yield return Environment.NewLine;
            }
        }
    }

    private static async Task ShowTeleprompter(TelePrompterConfig config)
    {
        var words = ReadFrom("sampleQuotes.txt");
        foreach (var word in words)
        {
            Console.Write(word);
            if (!string.IsNullOrWhiteSpace(word))
            {
                await Task.Delay(config.DelayInMilliseconds);
            }
        }
        config.SetDone();
    }

    private static async Task GetInput(TelePrompterConfig config)
    {
        Action work = () =>
        {
            do
            {
                var key = Console.ReadKey(true);
                if (key.KeyChar == '>')
                    config.UpdateDelay(-10);
                else if (key.KeyChar == '<')
                    config.UpdateDelay(10);
                else if (key.KeyChar == 'X' || key.KeyChar == 'x')
                    config.SetDone();
            } while (!config.Done);
        };
        await Task.Run(work);
    }
}

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

Hello World!
hello Lianhua
nihaoya
i am glad to meet you
hahahh
Once when I was six years old I saw a magnificent picture in a book, called
True Stories from Nature, about the primeval forest. It was a picture of
a boa constrictor in the act of swallowing an animal. Here is a copy of
the drawing.
In the book it said, "Boa constrictors swallow their prey whole, without
chewing it. After that they are not able to move, and they sleep through
the six months that they need for digestion."

I pondered deeply, then, over the adventures of the jungle. And after some
work with a colored pencil I succeeded in making my first drawing. My Drawing
Number One. It looked like this:
I showed my masterpiece to the grown-ups, and asked them whether the drawing
frightened them.

But they answered, "Frighten? Why should anyone be frightened by a hat?"


My drawing was not a picture of a hat. It was a picture of a boa constrictor
digesting an elephant. But since the grown-ups were not able to understand
it, I made another drawing: I drew the inside of the boa constrictor, so
that the grown-ups could see it clearly. They always need to have things
explained. My Drawing Number Two looked like this:

C:\...\ConsolePractice.exe (process 14244) exited with code 0.

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值