Synchronizing events from different threads in console application
You could try a BlockingCollection
BlockingCollection<Action> actions = new BlockingCollection<Action>();void main() { // start your tasks while (true) { var action = actions.Take(); action(); }}static void t_First(object sender, EventArgs e) { string message = "- first callback on:" + Thread.CurrentThread.ManagedThreadId; actions.Add(_ => Console.WriteLine(message));}
If I understand you right, you are asking about how to execute code running on thread into different thread. i.e: you have two threads, while you are executing the second thread code you want to execute it in the first thread.
You can achieve this by using SynchronizationContext
, for example if you want to execute code from another thread into main thread, you should use 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, using this method will execute code on the main thread.
you can implement ISynchronizeInvoke "System.ComponentModel.ISynchronizeInvoke". check this example.
Edit: Because of you are running a Console application and so can't use SynchronizationContext.Current
. then you probably need to design your own SynchronizationContext
, this example might help.