Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SynchronizationContext and InvokeRequired

I have been looking all over for an answer to this question, but can't seem to find a satisfactory answer. Maybe someone here can enlighten me.

I have a descendent of BindingList<T> that stores a reference to a SynchronizationContext object in order to raise its changed events on the UI thread.

Now, it's also possible that this BindingList<T> was created and used on the UI thread and not a background thread. How do I check this without a property like InvokeRequired available to me? What are the consequences of calling SynchronizationContext.Send on the UI thread?

like image 542
Dan Avatar asked Mar 28 '11 22:03

Dan


People also ask

What is SynchronizationContext in C#?

Simply put, SynchronizationContext represents a location "where" code might be executed. Delegates that are passed to its Send or Post method will then be invoked in that location. ( Post is the non-blocking / asynchronous version of Send .) Every thread can have a SynchronizationContext instance associated with it.

What is synchronous context?

SynchronizationContext is a representation of the current environment that our code is running in. That is, in an asynchronous program, when we delegate a unit of work to another thread, we capture the current environment and store it in an instance of SynchronizationContext and place it on Task object.


1 Answers

The Send method on SynchronizationContext will execute synchronously and call the delegate on the thread to which the SynchronizationContext is bound. If the SynchronizationContext is bound to the UI thread and the code is currently executing on the UI thread then the delegate will just be invoked directly with no need to marshal between threads.

like image 68
JaredPar Avatar answered Sep 17 '22 18:09

JaredPar