同步控制台应用程序中不同线程的事件

Urb*_*Esc 4 c# multithreading task console-application

我感觉自己像一个总的菜鸟问这个,但无论如何,它在这里:

我想知道从不同线程同步事件的最简单方法是什么.

一些示例代码:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("# started on:" + Thread.CurrentThread.ManagedThreadId);
        tt t = new tt();

        t.First += new EventHandler(t_First);
        t.Second += new EventHandler(t_Second);

        Task task = new Task(new Action(t.Test));
        task.Start();

        while (true)
        {
            Console.ReadKey();
            Console.WriteLine("# waiting on:" + Thread.CurrentThread.ManagedThreadId);
        }
    }

    static void t_Second(object sender, EventArgs e)
    {
        Console.WriteLine("- second callback on:" + Thread.CurrentThread.ManagedThreadId);
    }

    static void t_First(object sender, EventArgs e)
    {
        Console.WriteLine("- first callback on:" + Thread.CurrentThread.ManagedThreadId);
    }

    class tt
    {
        public tt()
        {
        }

        public event EventHandler First;
        public event EventHandler Second;

        public void Test()
        {
            Thread.Sleep(1000);

            Console.WriteLine("invoked on:" + Thread.CurrentThread.ManagedThreadId);

            First(this, null);
            Thread.Sleep(1000);
            Second(this, null);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您可能猜到的那样,只有第一个writeline在主线程上执行,其他调用都在任务创建的新线程上执行.

我想在主线程上同步调用"Second"(它应该永远不会被调用,因为我在while循环中阻塞).但是,我想知道这样做的方式,或者它是否可能?

adr*_*anm 6

你可以尝试一下 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));
}
Run Code Online (Sandbox Code Playgroud)