Invoke / BeginInvoke call from stream

I have a C # 2.0 application with a form that uses a class containing a stream.

In a stream function, rather than calling the event handler directly, it is called. The effect is that the owning form does not need to call InvokeRequired / BeginInvoke to update its controls.

public class Foo { private Control owner_; Thread thread_; public event EventHandler<EventArgs> FooEvent; public Foo(Control owner) { owner_ = owner; thread_ = new Thread(FooThread); thread_.Start(); } private void FooThread() { Thread.Sleep(1000); for (;;) { // Invoke performed in the thread owner_.Invoke((EventHandler<EventArgs>)InternalFooEvent, new object[] { this, new EventArgs() }); Thread.Sleep(10); } } private void InternalFooEvent(object sender, EventArgs e) { EventHandler<EventArgs> evt = FooEvent; if (evt != null) evt(sender, e); } } public partial class Form1 : Form { private Foo foo_; public Form1() { InitializeComponent(); foo_ = new Foo(this); foo_.FooEvent += OnFooEvent; } private void OnFooEvent(object sender, EventArgs e) { // does not need to call InvokeRequired/BeginInvoke() label_.Text = "hello"; } } 

This obviously contradicts the method used by the Microsoft API, which use background threads such as System.Timers.Timer and System.Io.Ports.SerialPort. Is there anything irreparable in this method? Is it dangerous in something?

Thanks PaulH


Edit: also, what if the form did not immediately subscribe to the event? Will it clog the message queue of the form with events that the form was not interested in?

+4
source share
1 answer

This is a streaming call, the method will be processed in the form stream.

Nothing wrong with that, if you look at it from a conceptual point of view.

Timers are more elegant for such tasks. However, it may happen that a timer with an interval of 10 ms slows down the GUI, which is why Invoke was probably used.

You do not need an InvokeRequired call, as it is clear that the control is in a different thread. In addition, BeginInvoke needs to be called only if you want to call the method asynchronously, which is clearly not the case.

Regarding your editing: No, the message queue will not be clogged. The event will not be fired if the handler is not registered. Look again at your code;)

+3
source

All Articles