Class with 2 events
public class Worker
{
// Created 2 events
public event EventHandler OnCompleted;
public event EventHandler<WorkerArgs> InBetween;
public void DoWork(int age, string address)
{
for (int i = 0; i < age - 1; i++)
{
Thread.Sleep(1000);
// Either this way
//var del= InBetween as EventHandler<WorkerArgs>;
//if (del != null) del(this,new WorkerArgs(i,address));
// Or Directly
if (InBetween != null) InBetween(this, new WorkerArgs(i, address));
}
OnCompleted(this, EventArgs.Empty);
}
}
Creating EventArgs
public class WorkerArgs : EventArgs
{
public int Age { get; set; }
public string Address { get; set; }
public WorkerArgs(int age,string address)
{
this.Age = age;
this.Address = address;
}
}
Main Class
class Program
{
static void Main(string[] args)
{
Worker w = new Worker();
w.InBetween += (s, arg) => {
Console.WriteLine("*");
};
w.OnCompleted += (s, arg) => {
Console.WriteLine("#");
};
w.DoWork(10,"Hello");
Console.Read();
}
}
Define the event handlers before the method is called..
Comments
Post a Comment