c# - Exploiting the BackGroundWorker for cross-thread invocation of GUI actions on Winforms controls? -


inspired own experience multithreaded winforms applications, questions such as

i've come simple pattern, soundness verify.

basically i'm creating (and running throughout application's lifetime) bgw sole purpose synchronization of invoke requests. consider:

public mainform() {     initializecomponent();     initinvocationsyncworker(); }  private void initinvocationsyncworker() {     invocationsync_worker.runworkerasync(); }  private void invocationsync_worker_dowork(object sender, doworkeventargs e) {     thread.sleep(timeout.infinite); }  void invokeviasyncworker(action guiaction) {     invocationsync_worker.reportprogress(0, guiaction); }  private void invocationsync_progresschanged(object sender, progresschangedeventargs e) {     if (isdisposed) return; //we're in gui thread now, no race condition right?      var action = (action) e.userstate;     action(); }  public void somemethodcalledfromanythread() //sample usage {     invokeviasyncworker(() => mytextbox.text = "hello thread!"));     } 

granted, it's not economical of approaches (keeping thread alive that), if works , haven't missed anything, sure simplest i've seen.

feedback highly appreciated !

there's no need open thread that. use synchronizationcontext, so:

private readonly synchronizationcontext _synccontext;  public mainform() {     initializecomponent();      _synccontext = synchronizationcontext.current; }  void invokeviasynccontext(action uiaction) {     _synccontext.post(o =>     {         if (ishandlecreated && !isdisposed) uiaction();     }, null); }  public void somemethodcalledfromanythread() //sample usage {     invokeviasynccontext(() => mytextbox.text = "hello thread!"));     } 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -