c# - Calling Invoke/BeginInvoke from a thread -


i have c# 2.0 application form uses class contains thread.

in thread function, rather call event handler directly, invoked. effect owning form not need call invokerequired/begininvoke update 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);         (;;)         {             // invoke performed in 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)     {         // not need call invokerequired/begininvoke()          label_.text = "hello";     } } 

this contrary method used microsoft apis use background threads system.timers.timer , system.io.ports.serialport. there inherently wrong method? dangerous in way?

thanks, paulh


edit: also, if form did not subscribe event right away? clog form's message queue events form wasn't interested in?

this threadsafe call, method processed in thread of form.

nothing wrong when looking @ conceptual perspective.

timers more elegant such tasks, though. however, timer interval of 10ms slows down gui, that's why invoke used.

you not need call invokerequired, since clear control in other thread. also, begininvoke needs called when want call method asynchronously, isn't case here.

regarding edit: no, message queue not clogged. no event fired if no handler has been registered. take @ code ;)


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -