Of course you can invoke a method on the other thread, more exactly, a delegate instance, but…
Your "stop what you're doing now, run this code, and than return to do your work" sounds like
thread preemption. Do you mean,
t1
should be agnostic to the code to be executed when it is to be interrupted? — it sounds like. If so, not that this is impossible, it cannot be attributed any meaning. Let's think about that. Preemption of a thread happens all the time — this is how threading works. Thread switching can be cooperative or can happen on hardware interrupts, and in all cases a thread can be preempted, its execution is interrupted, its context is saved, and some other code is executed. After a while, the same thread can be scheduled for execution again. From the perspective of this thread, nothing happened — execution is continued from the same point in the same environment. Basically, a thread "feels" like it is being executed along. But what code is running when a thread is switched off?
Anything but this thread, by definition. Interrupt procedure is executed, eventually a thread scheduler, anything in the system core needed to maintain threading, and other threads. Just think about it — this is the heart of the idea of threading.
When a thread is preempted, what is being executed at that time is not this thread.
Now, don't be fooled by the idea of thread invocation. It simply means that one thread feeds some delegate instanced to some other thread
specially designed to accept those instances and invoke them. An example of such thread is a UI thread, either
System.Windows.Forms
or WPF, but in principle it can be anything else. Keep reading; and I'll explain how it works. First, to get an idea on how invocation works on the UI threads, please read my past answers on this topic:
Control.Invoke() vs. Control.BeginInvoke()[
^],
Problem with Treeview Scanner And MD5[
^].
Many developers have been confused by the fact the the
Invoke/BeginInvoke
methods always works somehow, even if there is no UI thread. This is nothing more than the fool-proof design of the
System.Windows.Threading.Dispatcher
(please see
http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx[
^]). It is designed to invoke "dispatched" delegate instance in all cases, but in can be trivially invoked on the same thread, as simple as that.
To use inter-thread invocation to a thread other then a UI thread,
you need to specially design that thread to accept those delegate instances and invoke them. In particular, that thread needs to have a main processing loop and a queue where other threads can feed the delegate instances. If you need to understand how it works, please read my small article on this topic, complete with full source code and usage samples:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[
^].
—SA