如何通知子线程中事件的主线程?

时间:2013-05-22 07:02:05

标签: c# windows-phone-7

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

1 个答案:

答案 0 :(得分: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");
    }
}