Is there a Control.BeginInvoke option that works before / after the handle?

I have a control that displays the status of a basic asynchronous object. An object raises events that come into shape, where they are essentially queued and ultimately called using BeginInvoke.

The problem occurs when the control is placed. Since everything happens asynchronously, which means it is always possible that the event callback is queued during deletion, I sometimes get an InvalidOperationException (Invoke or BeginInvoke cannot be called in the control until the window handle is created.) .

This is not the behavior I want. I want the callback to be executed even if the control was removed (even if this throws an exception in the callback, this is a much more useful exception for me!). I want to handle the behavior of remote states in each callback (usually just skip if deleted, but sometimes not [for example, one control logs events (not necessarily to a file), and I don't want to lose log data!].).

Is there a method that works the way I want? Can I write non-fiction myself?

+4
source share
1 answer

Try SynchronizationContext.Current . It has Post and Send members, which roughly correspond to BeginInvoke and Invoke on Control . These operations will continue to function as long as the user interface thread is active against a specific control.

The SynchronizationContext type does not apply to WinForms, and its solutions will migrate to other environments such as WPF.

For instance.

BeginInvoke Code

 void OnButtonClicked() { DoBackgroundOperation(this); } void DoBackgroundOperation(ISynchronizedInvoke invoke) { ThreadPool.QueueUserWorkItem(delegate { ... delegate.BeginInovke(new MethodInvoker(this.BackgroundOperationComplete), null); }); } 

Sync Contact Code

 void OnButtonClicked() { DoBackgroundOperation(SynchronizationContext.Current); } void DoBackgroundOperation(SynchronizationContext context) { ThreadPool.QueueUserWorkItem(delegate { ... context.Post(delegate { this.BackgroundOperationComplete() }, null); }); } 
+6
source

Source: https://habr.com/ru/post/1333099/


All Articles