challenge 出力の一時停止と再開

起動すると、標準出力に1秒毎に'a'の1文字を出力し続けるプログラムで、 以下の条件を満たすものを「どう書く?」

  • 'q'キーが押されるとプログラムは終了する
  • 出力中に'p'キーが押されると一時停止する
  • 一時停止中に'p'キーが押されると出力を再開する

Posted feedbacks - C#

こんなんで題意に添えているでしょうか?
System.Timers.Timerクラスを使用しています。Timerクラスは指定した間隔でイベントを発生させます。
後はループを回して、その中でTimerの停止、再開を切り替えています。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;
using System.Timers;

class Program {
    static void Main(string[] args) {
        using(Timer timer = new Timer(1000)) {
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
            bool flag = true;
            while(flag) {
                ConsoleKeyInfo conKeyInfo = Console.ReadKey(true);
                ConsoleKey conKey = conKeyInfo.Key;
                switch(conKey) {
                case ConsoleKey.P:
                    timer.Enabled = !timer.Enabled;
                    break;
                case ConsoleKey.Q:
                    flag = false;
                    break;
                }
            }
           timer.Close();
        }
    }

    static void timer_Elapsed(object sender, ElapsedEventArgs e) {
        Console.Out.WriteLine("a");
    }
}

もしかして、こっちの方が期待通り?と思い、自前でマルチスレッドで書いてみました。
Timerクラス使うのと大差ないコード量ですね、若干挙動は違いますが。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Thread thread = new Thread(new System.Threading.ThreadStart(tick));
        thread.IsBackground = true;
        thread.Start();
        bool flag = true;
        while(flag) {
            switch(Console.ReadKey(true).Key) {
            case ConsoleKey.P:
                switch_ = !switch_;
                break;
            case ConsoleKey.Q:
                flag = false;
                break;
            }
        }
    }
    static bool switch_ = true;
    static void tick() {
        while(true) {
            if(switch_) {
                Console.Out.Write("a");
            }
            Thread.Sleep(1000);
        }
    }
}

Index

Feed

Other

Link

Pathtraq

loading...