Certain cross-threads calls are not allowed, by a number of reasons. You can easily delegate some methods to UI thread. This way, you can create an object in UI thread, and call all its methods in UI thread, but the calls are triggered in some other thread. This is the case when you call methods/properties related to the currently running UI — all such calls should be done in UI thread only. you need to use the method
Invoke
or
BeginInvoke
of
System.Windows.Threading.Dispatcher
(for both Forms or WPF) or
System.Windows.Forms.Control
(Forms only).
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[
^],
Problem with Treeview Scanner And MD5[
^].
See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[
^],
Control events not firing after enable disable + multithreading[
^].
By the way, if you needed to delegate some calls to non-UI thread, you would need to program that thread in a special way. You can understand how it works if you see my article:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[
^].
This small article is complete with full source code and detailed usage sample. Note that starting with .NET v.4.0, you could also use
System.Collections.Concurrent.BlockingCollection<T>
:
http://msdn.microsoft.com/en-us/library/dd267312.aspx[
^].
See also the alternative to my article referenced above. The benefit of my article is that I explain how it works under the hood and the usage, but Microsoft class is better in performance.
—SA