委托与事件
public abstract class AbstractThread
{
Thread thread = null;
public abstract void run();
public void start()
{
if (thread == null)
thread = new Thread(new ThreadStart(run));
thread.Start();
}
}
{
Thread thread = null;
public abstract void run();
public void start()
{
if (thread == null)
thread = new Thread(new ThreadStart(run));
thread.Start();
}
}
public delegate void TimeEventHandler(object obj, TimeEventArgs args);
public class EventThread : AbstractThread
{
public EventThread()
{
IsAlive = true;
}
public event TimeEventHandler TimeChanged;
public bool IsAlive { get; set; }
public override void run()
{
DateTime initi = DateTime.Now;
int h1 = initi.Hour;
int m1 = initi.Minute;
int s1 = initi.Second;
while (IsAlive)
{
DateTime now = DateTime.Now;
int h2 = now.Hour;
int m2 = now.Minute;
int s2 = now.Second;
if (s2 != s1)
{
h1 = h2;
m1 = m2;
s1 = s2;
//首先建立一个TimeEventArgs对象来保存相关参数,这里是时分秒。
TimeEventArgs args = new TimeEventArgs(h2, m2, s2);
TimeChanged(this, args);
}
Thread.Sleep(1000);
}
}
}
public class TimeEventArgs : EventArgs
{
private int hour;
private int minute;
private int second;
public TimeEventArgs(int hour, int minute, int second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public int Hour
{
get
{
return hour;
}
}
public int Minute
{
get
{
return minute;
}
}
public int Second
{
get
{
return second;
}
}
}
public class EventThread : AbstractThread
{
public EventThread()
{
IsAlive = true;
}
public event TimeEventHandler TimeChanged;
public bool IsAlive { get; set; }
public override void run()
{
DateTime initi = DateTime.Now;
int h1 = initi.Hour;
int m1 = initi.Minute;
int s1 = initi.Second;
while (IsAlive)
{
DateTime now = DateTime.Now;
int h2 = now.Hour;
int m2 = now.Minute;
int s2 = now.Second;
if (s2 != s1)
{
h1 = h2;
m1 = m2;
s1 = s2;
//首先建立一个TimeEventArgs对象来保存相关参数,这里是时分秒。
TimeEventArgs args = new TimeEventArgs(h2, m2, s2);
TimeChanged(this, args);
}
Thread.Sleep(1000);
}
}
}
public class TimeEventArgs : EventArgs
{
private int hour;
private int minute;
private int second;
public TimeEventArgs(int hour, int minute, int second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public int Hour
{
get
{
return hour;
}
}
public int Minute
{
get
{
return minute;
}
}
public int Second
{
get
{
return second;
}
}
}