If you understand correctly, you are asking how to execute code that runs on a thread in another thread. ie: you have two threads, while you are executing the second code of the thread that you want to execute in the first thread.
You can achieve this using a SynchronizationContext , for example, if you want to execute code from another thread into the main thread, you should use the current synchronization context:
private readonly System.Threading.SynchronizationContext _currentContext = System.Threading.SynchronizationContext.Current; private readonly object _invokeLocker = new object(); public object Invoke(Delegate method, object[] args) { if (method == null) { throw new ArgumentNullException("method"); } lock (_invokeLocker) { object objectToGet = null; SendOrPostCallback invoker = new SendOrPostCallback( delegate(object data) { objectToGet = method.DynamicInvoke(args); }); _currentContext.Send(new SendOrPostCallback(invoker), method.Target); return objectToGet; } }
While you are in the second thread, this method will execute the code in the main thread.
you can implement ISynchronizeInvoke "System.ComponentModel.ISynchronizeInvoke". check out this example.
Edit: Due to the fact that you are using a console application and therefore cannot use SynchronizationContext.Current . then you will probably need to create your own SynchronizationContext , this example that may help.
source share