Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In Windows Forms, calling <code>Invoke</code> on some control (such as your main form) will indeed throw if that control is disposed (e.g. the user closed the form). A simple way to avoid it would be using the winforms <code>SynchronizationContext</code> class. This works because the <code>WindowsFormsSynchronizationContext</code> keeps an internal control of its own, on which it calls the <code>Invoke</code>/<code>BeginInvoke</code> commands. see <a href="https://stackoverflow.com/questions/4190299/exploiting-the-backgroundworker-for-cross-thread-invocation-of-gui-actions-on-win/4192954">Exploiting the BackGroundWorker for cross-thread invocation of GUI actions on Winforms controls?</a></p> <p>In WPF, the <code>SynchronizationContext</code> delegates to the dispatcher so using either of them is the same. However, since the WPF dispatcher is not disposable as controls are (it can be shut down though), you don't have to worry about an <code>ObjectDisposedException</code>. However, I believe calling <code>Invoke</code> may hang your application if the dispatcher has been shut down (since it would wait for an operation that would never complete) - calling <code>BeginInvoke</code> instead should take care of that. That being said, ThreadPool threads (which are the ones created by the default Task scheduler, as in your case above) are Background threads which would not stop your process from exiting - even if they are hung on a <code>Dispatcher.Invoke</code> call.</p> <p>In short, in both Windows Forms and WPF, using <code>SynchronizationContext.Post</code> (which in WPF is equivalent to <code>Dispatcher.BeginInvoke</code>) will take care of the general problem you're talking about.</p> <p><strong>Let's change the scenario a bit - what happens when the user closes the form while the UI is being updated in the Dispatcher.Invoke routine?</strong> That can't happen - while the <code>Dispatcher.Invoke</code> invoke is running the UI thread is busy, in particular it can't process user input such as the keyboard or mouse click a user would need to close the form.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload