방법: 이벤트 발생 및 사용
이 문서의 예제에서는 이벤트로 작업하는 방법을 보여 줍니다. 여기서 EventHandler 대리자, EventHandler<TEventArgs> 대리자 및 사용자 지정 대리자의 예제를 통해 데이터를 사용하거나 사용하지 않는 이벤트를 설명합니다.
이 예제에서는 이벤트 문서에 설명된 개념을 사용합니다.
예 1
첫 번째 예제에서는 데이터가 없는 이벤트를 발생시키고 사용하는 방법을 보여 줍니다. 이벤트의 이름이 ThresholdReached
인 Counter
라는 클래스를 포함합니다. 이 이벤트는 카운터 값이 같거나 임계값을 초과할 때 발생합니다. 이벤트 데이터가 제공되지 않았으므로 EventHandler 대리자는 이벤트와 연결됩니다.
using System;
namespace ConsoleApplication1
{
class ProgramOne
{
static void Main(string[] args)
{
Counter c = new Counter(new Random().Next(10));
c.ThresholdReached += c_ThresholdReached;
Console.WriteLine("press 'a' key to increase total");
while (Console.ReadKey(true).KeyChar == 'a')
{
Console.WriteLine("adding one");
c.Add(1);
}
}
static void c_ThresholdReached(object sender, EventArgs e)
{
Console.WriteLine("The threshold was reached.");
Environment.Exit(0);
}
}
class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
if (total >= threshold)
{
ThresholdReached?.Invoke(this, EventArgs.Empty);
}
}
public event EventHandler ThresholdReached;
}
}
Module Module1
Sub Main()
Dim c As Counter = New Counter(New Random().Next(10))
AddHandler c.ThresholdReached, AddressOf c_ThresholdReached
Console.WriteLine("press 'a' key to increase total")
While Console.ReadKey(True).KeyChar = "a"
Console.WriteLine("adding one")
c.Add(1)
End While
End Sub
Sub c_ThresholdReached(sender As Object, e As EventArgs)
Console.WriteLine("The threshold was reached.")
Environment.Exit(0)
End Sub
End Module
Class Counter
Private threshold As Integer
Private total As Integer
Public Sub New(passedThreshold As Integer)
threshold = passedThreshold
End Sub
Public Sub Add(x As Integer)
total = total + x
If (total >= threshold) Then
ThresholdReached?.Invoke(this. EventArgs.Empty)
End If
End Sub
Public Event ThresholdReached As EventHandler
End Class
예제 2
두 번째 예제에서는 데이터를 제공하는 이벤트를 발생시키고 사용하는 방법을 보여 줍니다. EventHandler<TEventArgs> 대리자가 이벤트와 연결되었으며 사용자 지정 이벤트 데이터 개체의 인스턴스가 제공되었습니다.
using namespace System;
public ref class ThresholdReachedEventArgs : public EventArgs
{
public:
property int Threshold;
property DateTime TimeReached;
};
public ref class Counter
{
private:
int threshold;
int total;
public:
Counter() {};
Counter(int passedThreshold)
{
threshold = passedThreshold;
}
void Add(int x)
{
total += x;
if (total >= threshold) {
ThresholdReachedEventArgs^ args = gcnew ThresholdReachedEventArgs();
args->Threshold = threshold;
args->TimeReached = DateTime::Now;
OnThresholdReached(args);
}
}
event EventHandler<ThresholdReachedEventArgs^>^ ThresholdReached;
protected:
virtual void OnThresholdReached(ThresholdReachedEventArgs^ e)
{
ThresholdReached(this, e);
}
};
public ref class SampleHandler
{
public:
static void c_ThresholdReached(Object^ sender, ThresholdReachedEventArgs^ e)
{
Console::WriteLine("The threshold of {0} was reached at {1}.",
e->Threshold, e->TimeReached);
Environment::Exit(0);
}
};
void main()
{
Counter^ c = gcnew Counter((gcnew Random())->Next(10));
c->ThresholdReached += gcnew EventHandler<ThresholdReachedEventArgs^>(SampleHandler::c_ThresholdReached);
Console::WriteLine("press 'a' key to increase total");
while (Console::ReadKey(true).KeyChar == 'a') {
Console::WriteLine("adding one");
c->Add(1);
}
}
using System;
namespace ConsoleApplication3
{
class ProgramThree
{
static void Main(string[] args)
{
Counter c = new Counter(new Random().Next(10));
c.ThresholdReached += c_ThresholdReached;
Console.WriteLine("press 'a' key to increase total");
while (Console.ReadKey(true).KeyChar == 'a')
{
Console.WriteLine("adding one");
c.Add(1);
}
}
static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
{
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
Environment.Exit(0);
}
}
class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
if (total >= threshold)
{
ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
args.Threshold = threshold;
args.TimeReached = DateTime.Now;
OnThresholdReached(args);
}
}
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
if (handler != null)
{
handler(this, e);
}
}
public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
}
public class ThresholdReachedEventArgs : EventArgs
{
public int Threshold { get; set; }
public DateTime TimeReached { get; set; }
}
}
Module Module1
Sub Main()
Dim c As Counter = New Counter(New Random().Next(10))
AddHandler c.ThresholdReached, AddressOf c_ThresholdReached
Console.WriteLine("press 'a' key to increase total")
While Console.ReadKey(True).KeyChar = "a"
Console.WriteLine("adding one")
c.Add(1)
End While
End Sub
Sub c_ThresholdReached(sender As Object, e As ThresholdReachedEventArgs)
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached)
Environment.Exit(0)
End Sub
End Module
Class Counter
Private threshold As Integer
Private total As Integer
Public Sub New(passedThreshold As Integer)
threshold = passedThreshold
End Sub
Public Sub Add(x As Integer)
total = total + x
If (total >= threshold) Then
Dim args As ThresholdReachedEventArgs = New ThresholdReachedEventArgs()
args.Threshold = threshold
args.TimeReached = DateTime.Now
OnThresholdReached(args)
End If
End Sub
Protected Overridable Sub OnThresholdReached(e As ThresholdReachedEventArgs)
RaiseEvent ThresholdReached(Me, e)
End Sub
Public Event ThresholdReached As EventHandler(Of ThresholdReachedEventArgs)
End Class
Class ThresholdReachedEventArgs
Inherits EventArgs
Public Property Threshold As Integer
Public Property TimeReached As DateTime
End Class
예제 3
세 번째 예제에서는 이벤트의 대리자를 선언하는 방법을 보여 줍니다. 대리자의 이름은 ThresholdReachedEventHandler
입니다. 이 예제는 그림으로 나타낸 것일 뿐입니다. 일반적으로 이벤트에 대한 대리자를 선언할 필요가 없습니다. EventHandler 또는 EventHandler<TEventArgs> 대리자 중 하나를 사용할 수 있기 때문입니다. 대리자는 제네릭을 사용할 수 없는 레거시 코드에서 클래스를 사용할 수 있는 경우와 같이 드문 시나리오에서만 선언해야 합니다.
using System;
namespace ConsoleApplication4
{
class ProgramFour
{
static void Main(string[] args)
{
Counter c = new Counter(new Random().Next(10));
c.ThresholdReached += c_ThresholdReached;
Console.WriteLine("press 'a' key to increase total");
while (Console.ReadKey(true).KeyChar == 'a')
{
Console.WriteLine("adding one");
c.Add(1);
}
}
static void c_ThresholdReached(Object sender, ThresholdReachedEventArgs e)
{
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
Environment.Exit(0);
}
}
class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
if (total >= threshold)
{
ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
args.Threshold = threshold;
args.TimeReached = DateTime.Now;
OnThresholdReached(args);
}
}
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
ThresholdReachedEventHandler handler = ThresholdReached;
if (handler != null)
{
handler(this, e);
}
}
public event ThresholdReachedEventHandler ThresholdReached;
}
public class ThresholdReachedEventArgs : EventArgs
{
public int Threshold { get; set; }
public DateTime TimeReached { get; set; }
}
public delegate void ThresholdReachedEventHandler(Object sender, ThresholdReachedEventArgs e);
}
Module Module1
Sub Main()
Dim c As Counter = New Counter(New Random().Next(10))
AddHandler c.ThresholdReached, AddressOf c_ThresholdReached
Console.WriteLine("press 'a' key to increase total")
While Console.ReadKey(True).KeyChar = "a"
Console.WriteLine("adding one")
c.Add(1)
End While
End Sub
Sub c_ThresholdReached(sender As Object, e As ThresholdReachedEventArgs)
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached)
Environment.Exit(0)
End Sub
End Module
Class Counter
Private threshold As Integer
Private total As Integer
Public Sub New(passedThreshold As Integer)
threshold = passedThreshold
End Sub
Public Sub Add(x As Integer)
total = total + x
If (total >= threshold) Then
Dim args As ThresholdReachedEventArgs = New ThresholdReachedEventArgs()
args.Threshold = threshold
args.TimeReached = DateTime.Now
OnThresholdReached(args)
End If
End Sub
Protected Overridable Sub OnThresholdReached(e As ThresholdReachedEventArgs)
RaiseEvent ThresholdReached(Me, e)
End Sub
Public Event ThresholdReached As ThresholdReachedEventHandler
End Class
Public Class ThresholdReachedEventArgs
Inherits EventArgs
Public Property Threshold As Integer
Public Property TimeReached As DateTime
End Class
Public Delegate Sub ThresholdReachedEventHandler(sender As Object, e As ThresholdReachedEventArgs)
참조
.NET