0

我有一个子线程,在某个时间后触发事件,所以当事件在子线程中触发时,我如何通知主线程并在主线程中调用函数?

4

1 回答 1

2

您可以使用WaitHandle派生类在主线程和子线程之间进行通信:

class Program
{
    static void Main(string[] args)
    {
        ManualResetEvent handle = new ManualResetEvent(false);
        Thread thread = new Thread(o =>
            {
                WorkBeforeEvent();
                handle.Set();
                WorkAfterEvent();
                Console.WriteLine("Child Thread finished");

            });
        thread.Start();

        Console.WriteLine("Main Thread waiting for event from child");
        handle.WaitOne();
        Console.WriteLine("Main Thread notified of event from child");

        Console.ReadLine();
    }

    public static void WorkBeforeEvent()
    {
        Thread.Sleep(1000);
        Console.WriteLine("Before Event");
    }

    public static void WorkAfterEvent()
    {
        Thread.Sleep(1000);
        Console.WriteLine("After Event");
    }
}
于 2013-05-22T09:52:59.547 回答