Synchronizing events from different threads in console application

青春壹個敷衍的年華 提交于 2019-12-05 15:22:07

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));
}
Jalal Said

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!