やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

C#チュートリアル(コンソールアプリケーション)

 内容はおもに非同期についてだった。これは超便利。勉強しておくべき。

成果物

情報源

プロジェクト作成

dotnet new console -o TeleprompterConsole
cd TeleprompterConsole

sampleQuotes.txt

sampleQuotes.txt

1. You can do anything, but not everything.

-David Allen


2. Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.

-Antoine de Saint-Exupéry


3. The richest man is not he who has the most, but he who needs the least.

-Unknown Author


4. You miss 100 percent of the shots you never take.

-Wayne Gretzky


5. Courage is not the absence of fear, but rather the judgement that something else is more important than fear.

-Ambrose Redmoon


6. You must be the change you wish to see in the world.

-Gandhi


7. When hungry, eat your rice; when tired, close your eyes. Fools may laugh at me, but wise men will know what I mean.

-Lin-Chi


8. The third-rate mind is only happy when it is thinking with the majority. The second-rate mind is only happy when it is thinking with the minority. The first-rate mind is only happy when it is thinking.

-A. A. Milne


9. To the man who only has a hammer, everything he encounters begins to look like a nail.

-Abraham Maslow


10. We are what we repeatedly do; excellence, then, is not an act but a habit.

-Aristotle


11. A wise man gets more use from his enemies than a fool from his friends.

-Baltasar Gracian


12. Do not seek to follow in the footsteps of the men of old; seek what they sought.

-Basho


13. Watch your thoughts; they become words.
Watch your words; they become actions.
Watch your actions; they become habits.
Watch your habits; they become character.
Watch your character; it becomes your destiny.

-Lao-Tze


14. Everyone is a genius at least once a year. The real geniuses simply have their bright ideas closer together.

-Georg Christoph Lichtenberg


15. What we think, or what we know, or what we believe is, in the end, of little consequence. The only consequence is what we do.

-John Ruskin


16. The real voyage of discovery consists not in seeking new lands but seeing with new eyes.

-Marcel Proust


17. Work like you don't need money, love like you've never been hurt, and dance like no one's watching

-Unknown Author


18. Try a thing you haven't done three times. Once, to get over the fear of doing it. Twice, to learn how to do it. And a third time, to figure out whether you like it or not.

-Virgil Garnett Thomson


19. Even if you're on the right track, you'll get run over if you just sit there.

-Will Rogers


20. People often say that motivation doesn't last. Well, neither does bathing – that's why we recommend it daily.

-Zig Ziglar


21. Before I got married I had six theories about bringing up children; now I have six children and no theories.

-John Wilmot


22. What the world needs is more geniuses with humility, there are so few of us left.

-Oscar Levant


23. Always forgive your enemies; nothing annoys them so much.

-Oscar Wilde


24. I've gone into hundreds of [fortune-teller's parlors], and have been told thousands of things, but nobody ever told me I was a policewoman getting ready to arrest her.

-New York City detective


25. When you go into court you are putting your fate into the hands of twelve people who weren't smart enough to get out of jury duty.

-Norm Crosby


26. Those who believe in telekinetics, raise my hand.

-Kurt Vonnegut


27. Just the fact that some geniuses were laughed at does not imply that all who are laughed at are geniuses. They laughed at Columbus, they laughed at Fulton, they laughed at the Wright brothers. But they also laughed at Bozo the Clown.

-Carl Sagan


28. My pessimism extends to the point of even suspecting the sincerity of the pessimists.

-Jean Rostand


29. Sometimes I worry about being a success in a mediocre world.

-Lily Tomlin


30. I quit therapy because my analyst was trying to help me behind my back.

-Richard Lewis


31. We've heard that a million monkeys at a million keyboards could produce the complete works of Shakespeare; now, thanks to the Internet, we know that is not true.

-Robert Wilensky


32. If there are no stupid questions, then what kind of questions do stupid people ask? Do they get smart just in time to ask questions?

-Scott Adams


33. If the lessons of history teach us anything it is that nobody learns the lessons that history teaches us.

-Anon


34. When I was a boy I was told that anybody could become President. Now I'm beginning to believe it.

-Clarence Darrow


35. Laughing at our mistakes can lengthen our own life. Laughing at someone else's can shorten it.

-Cullen Hightower


36. There are many who dare not kill themselves for fear of what the neighbors will say.

-Cyril Connolly


37. There's so much comedy on television. Does that cause comedy in the streets?

-Dick Cavett


38. All men are frauds. The only difference between them is that some admit it. I myself deny it.

-H. L. Mencken


39. I don't mind what Congress does, as long as they don't do it in the streets and frighten the horses.

-Victor Hugo


40. I took a speed reading course and read "War and Peace" in twenty minutes. It involves Russia.

-Woody Allen

41. The person who reads too much and uses his brain too little will fall into lazy habits of thinking.

-Albert Einstein


42. Believe those who are seeking the truth. Doubt those who find it.

-André Gide


43. It is the mark of an educated mind to be able to entertain a thought without accepting it.

-Aristotle


44. I'd rather live with a good question than a bad answer.

-Aryeh Frimer


45. We learn something every day, and lots of times it's that what we learned the day before was wrong.

-Bill Vaughan


46. I have made this letter longer than usual because I lack the time to make it shorter.

-Blaise Pascal


47. An inventor is simply a fellow who doesn't take his education too seriously.

-Charles F. Kettering


48. Asking a working writer what he thinks about critics is like asking a lamppost how it feels about dogs.

-Christopher Hampton


49. Better to write for yourself and have no public, than to write for the public and have no self.

-Cyril Connolly


50. Never be afraid to laugh at yourself, after all, you could be missing out on the joke of the century.

-Dame Edna Everage


51. I am patient with stupidity but not with those who are proud of it.

-Edith Sitwell


52. Normal is getting dressed in clothes that you buy for work and driving through traffic in a car that you are still paying for – in order to get to the job you need to pay for the clothes and the car, and the house you leave vacant all day so you can afford to live in it.

-Ellen Goodman


53. The cure for boredom is curiosity. There is no cure for curiosity.

-Ellen Parr


54. Advice is what we ask for when we already know the answer but wish we didn't.

-Erica Jong


55. Some people like my advice so much that they frame it upon the wall instead of using it.

-Gordon R. Dickson


56. Never ascribe to malice, that which can be explained by incompetence.

-Napoleon (Hanlon's Razor)


57. Imagination was given to man to compensate him for what he is not, and a sense of humor was provided to console him for what he is.

-Oscar Wilde


58. When a person can no longer laugh at himself, it is time for others to laugh at him.

-Thomas Szasz

コード

Program.cs

using System;

namespace TeleprompterConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            new Code5().Run();
        }
    }
}

Code5.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using static System.Math;

namespace TeleprompterConsole
{
    class Code5
    {
        public void Run()
        {
            RunTeleprompter().Wait();
        }
        private async Task RunTeleprompter()
        {
            var config = new TelePrompterConfig();
            var displayTask = ShowTeleprompter(config);

            var speedTask = GetInput(config);
            await Task.WhenAny(displayTask, speedTask);
        }
        private 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 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 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);
        }
    }
    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;
        }
    }
}

実行結果

dotnet run
  • sampleQuotes.txtファイルにあるテキストを、単語(スペース区切り)単位で表示する
  • 200ms/1単語 の速さで表示する
  • キー入力受付する
    • <: +10ms(減速)
    • >: -10ms(加速)
    • x: 終了

 Task単位に分離できるのがポイント。古い記法ならメインループに表示、入力受付などすべての処理を書く必要があり、分離できなかった。

要点

  • async/await
    • async Task メソッド名() { await Task.Deley(200); }
    • async Task メソッド名() { await Task.Run(Action); }
    • async Task メソッド名() { await Task.WhenAny(task1, task2); }

 遅延表示をしながら入力を受け付ける。

所感

 非同期やTaskがかなり強力っぽい。ちょっと難しそうだけど。いずれマスターしたい。

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1218 SMP Tue May 14 00:48:17 BST 2019 armv7l GNU/Linux