Sync Context and InvokeRequired

I searched all the time for the answer to this question, but did not seem to find a satisfactory answer. Maybe someone here can enlighten me.

I have a descendant of BindingList<T> that stores a reference to a SynchronizationContext object in order to raise its changed events in a user interface thread.

Now it is also possible that this BindingList<T> was created and used in the user interface thread, and not in the background thread. How can I check this without having a property of type InvokeRequired ? What are the implications of calling SynchronizationContext.Send in a user interface thread?

+4
source share
2 answers

The dispatch method on the SynchronizationContext will execute synchronously and will call delegane in the thread to which the SynchronizationContext bound. If the SynchronizationContext bound to a user interface thread and the code is currently executing in the user interface thread, then the delegate will simply be called directly, without having to marshal between threads.

+2
source

The submit method will execute synchronously, and true in the user interface thread. However, one possible concern is that a Send call expands the call stack.

So, for example, the following code:

 for (int i = 0; i < 10000000; i++) syncContext.Send(....); 

will result in a StackOverflow exception ... So it would be wise to avoid using a synchronization context if you are already using the right thread. I don’t know a single full-fledged way to check which stream was created in the list, in addition to performing internal accounting statements.

-1
source

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


All Articles