如何将子线程中的事件通知主线程
本文关键字:线程 事件 通知 | 更新日期: 2023-09-27 18:14:51
我有一个子线程,其中一个事件在一定时间后被触发,所以当事件在子线程中被触发时,我如何才能通知主线程相同并在主线程中调用函数?
您可以使用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");
}
}