Hi to all,
I'm trying to understand well the paradigm of Event and Delegates, but I've some problem that I can't explain to myself.
I've tried to write a little piece of code: in one class (the publisher) I declare a delegate and an public event, so someone can subscribe to it.
In another class (the subscriber) I create an instance of the publisher class, and add its method to be executed when the event is raised.
If I do this using a Windows Forms, when the event is raised up, I receive the message that I'm using Cross-Threading operation that is not a good think (I know how to disable the message, but is not what I want).
Here the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Timers;
namespace ProvaDelegateEvent
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Class1 instance = new Class1();
//subscribe myself to event generate from the instance obj and I give it its own
//manager, the method executed when the event is raised
instance.somethingHappens += new MyDelegate(EventHandler);
}
private void EventHandler()
{
textBox1.Text = "Event raised";
}
}
public delegate void MyDelegate();
public class Class1
{
//Public event where someone can subscribe itself and be advised when the event is raised
public event MyDelegate somethingHappens;
private System.Timers.Timer _tempor;
private int _second;
public Class1()
{
_tempor = new System.Timers.Timer(1000);
_tempor.Elapsed += new ElapsedEventHandler(tempor_Elapsed);
_tempor.Start();
}
private void tempor_Elapsed(object sender, ElapsedEventArgs e)
{
_second++;
if (_second == 3)
method(10, 10);
}
public void method(int i, int j)
{
EventArgs args = new EventArgs();
MyDelegate handler = somethingHappens;
if (i * j == 100)
handler.Invoke();
}
}
}
Instead of this, if I comment the line when I start the timer into the Class1 class, and call the method that raise the event directly in the Form constructor, in this way:
public Form1()
{
InitializeComponent();
Class1 instance = new Class1();
//subscribe myself to event generate from the instance obj and I give it its own
//manager, the method executed when the event is raised
instance.somethingHappens += new MyDelegate(EventHandler);
instance.method(10,10);
}
I don't have problem, all work greatly because the event is raised up from the thread that want to react it. But I want to be advertised indipendently of this, without be the cause of the raise of event.
How can I manage it?
Thank you very much
