開発環境
- OS: Windows 10 Pro
- IDE(統合開発環境): Visual Studio Community 2017
初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)、日向 俊二 (翻訳)、オライリージャパン)の17章(デリゲートとイベント)、17.6(練習問題)、練習17-3.を取り組んでみる。
コード
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 countDown1 = new CountDownEvent("経過1", 0, 0, 10);
CountDownEvent countDown2 = new CountDownEvent("経過2", 0, 0, 10);
Observer observer = new Observer();
observer.Subscribe(countDown1);
observer.Subscribe(countDown1);
countDown1.Run();
countDown2.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 event 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 経過1 経過1 続行するには何かキーを押してください . . .
0 コメント:
コメントを投稿