Using BackGroundWorker to loop through GUI actions on Winforms controls?

Inspired by my experience with multi-threaded Winforms applications, as well as issues such as

  • Avoid Invoke / BeginInvoke issues in event handling with end-to-end WinForm threads?
  • Avoid Invoke Calls When Placing a Control

I came up with a very simple template whose core I want to test.

Basically, I create (and execute all my life throughout the entire application) BGW, whose sole purpose is to synchronize call 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 the GUI thread now, so no race condition right? var action = (Action) e.UserState; action(); } public void SomeMethodCalledFromAnyThread() //Sample usage { InvokeViaSyncWorker(() => MyTextBox.Text = "Hello from another thread!")); } 

Of course, this is not the most economical of the approaches (supporting the stream in the same way), but if it works and I did not miss anything, this is by far the easiest I have seen.

Feedback is greatly appreciated!

+1
synchronization c # backgroundworker winforms
Nov 16 '10 at 0:56
source share
1 answer

There is no need to open the stream just for this. Just use SynchronizationContext , for example:

 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 from another thread!")); } 
+6
Nov 16 '10 at 10:02
source share
โ€” -



All Articles