2018年6月17日日曜日

開発環境

初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)日向 俊二 (翻訳)、オライリージャパン)の17章(デリゲートとイベント)、17.6(練習問題)、練習17-1.を取り組んでみる。

コード

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            CountDownEvent countDown = new CountDownEvent("経過", 0, 0, 10);
            Observer observer = new Observer();

            observer.Subscribe(countDown);
            countDown.Run();
        }
    }

    public class CountDownEventArgs : EventArgs
    {
        public readonly string message;

        public CountDownEventArgs(string message)
        {
            this.message = message;
        }
    }
    public class CountDownEvent
    {
        private DateTime start;
        private DateTime stop;
        private string message;

        public CountDownEvent
            (string message, int hours, int minutes, int seconds)
        {
            this.message = message;
            start = DateTime.Now;
            stop = start + new TimeSpan(hours, minutes, seconds);
        }

        public delegate void CountDownEventHandler
            (object obj, CountDownEventArgs countDownEventArgs);

        public CountDownEventHandler countDownEventHandler;

        public void Run()
        {
            int s = DateTime.Now.Second;
            int i = 0;
            while (true)
            {
                Thread.Sleep(10);

                DateTime dateTime = DateTime.Now;

                if (s != dateTime.Second)
                {
                    Console.WriteLine(i);

                    s += 1;
                    i += 1;
                }

                if (dateTime >= stop)
                {
                    if (countDownEventHandler != null)
                    {
                        CountDownEventArgs countDownEventArgs
                            = new CountDownEventArgs(message);
                        countDownEventHandler(this, countDownEventArgs);
                        break;
                    }
                }
            }
        }
    }
    
    public class Observer
    {
        public void Display(object countDown, CountDownEventArgs args)
        {
            Console.WriteLine(args.message);
        }
        public void Subscribe(CountDownEvent countDown)
        {
            countDown.countDownEventHandler +=
                new CountDownEvent.CountDownEventHandler(Display);
        }
    }
}

入出力結果(コマンドプロンプト)

0
1
2
3
4
5
6
7
8
9
経過
続行するには何かキーを押してください . . .

0 コメント:

コメントを投稿