One word: delegates.
for example:
Code:
public delegate void OnChange(string data);
You can pass a method that has a signature as follows to this delegate.
Code:
public void Bla(string d);
So suppose you have a class as follows:
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleTest {
public delegate void OnChange(string data);
class EventTest {
public OnChange Update;
private Thread t;
private int[] ar;
private int fireEvent;
public EventTest(int members,int fireEventMember) {
ar = new int[members];
this.fireEvent = fireEventMember;
t = new Thread(new ThreadStart(this.Run));
t.IsBackground = true;
t.Start();
}
public void Run() {
while (true) {
for (int i = 0; i < ar.Length; i++) {
if(i==this.fireEvent) {
this.Update(i.ToString());
}
}
Thread.Sleep(500);
}
}
}
}
Now each time i==this.fireEvent is true Update is called.
Upto now all of this is pretty useless ... unless we do something with Update...
So in our Program class we write.
Code:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleTest {
class Program {
static void Main(string[] args) {
Program p = new Program();
EventTest test = new EventTest(10, 5);
test.Update = new OnChange(p.Display);
test.Update += new OnChange(p.DisplaySecond);
Console.ReadLine();
test.Update -= new OnChange(p.DisplaySecond);
Console.ReadLine();
}
public void Display(string d) {
Console.WriteLine("From method 1: " +d);
}
public void DisplaySecond(string d) {
Console.WriteLine("From method 2: " + d);
}
}
}
So we actually give the meaning of what should happen in Program. Each time Update is called the methode Display should be executed.
Subscribing and un- is done trough += and -= .
If you dont understand any of this, search for some delegate tutorials....