gpt4 book ai didi

c# - 如何在 C# 线程中使用等待句柄?

转载 作者:行者123 更新时间:2023-11-30 13:28:27 24 4
gpt4 key购买 nike

我的程序中有三个线程,我希望当线程 1 完成时,它会通知线程 2 启动,而当线程 2 完成时,它会通知线程 3 启动。

我怎样才能做到这一点,我知道在 C# 中有等待句柄可以做到这一点,但我不知道如何使用它们?

以下是我的程序代码:

class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(Task1);
Thread t2 = new Thread(Task2);
Thread t3 = new Thread(Task3);

t1.Start();
t2.Start();
t3.Start();

Console.Read();
}

public static void Task1()
{
Console.WriteLine("I am assigned task 1:");
for (int i = 0; i < 50; i++)
{
Console.WriteLine("Task1" );
}
}
public static void Task2()
{
Console.WriteLine("I am assigned task 2:");
for (int i = 0; i < 50; i++)
{
Console.WriteLine("Task2");
}
}
public static void Task3()
{
Console.WriteLine("I am assigned task 3:");
for (int i = 0; i < 50; i++)
{
Console.WriteLine("Task3");
}
}
}

最佳答案

您需要将事件传递到线程函数中,以指示在每个函数完成时发出什么信号以及在它们运行之前要等待什么。看看下面的(未经测试的)代码,看看我的意思:

class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(Task1);
ManualResetEvent e1=new ManualResetEvent(false);

Thread t2 = new Thread(Task2);
ManualResetEvent e2=new ManualResetEvent(false);

Thread t3 = new Thread(Task3);
ManualResetEvent e3=new ManualResetEvent(false);

t1.Start(()=>Task1(e1));
t2.Start(()=>Task2(e1,e2));
t3.Start(()=>Task3(e2,e3);

Console.Read();

t1.Join();
t2.Join();
t3.Join();
}

public static void Task1(EventWaitHandle handle)
{
Console.WriteLine("I am assigned task 1:");
for (int i = 0; i < 50; i++)
{
Console.WriteLine("Task1" );
}
handle.Set();

}
public static void Task2(EventWaitHandle waitFor, EventWaitHandle handle)
{
waitFor.WaitOne();

Console.WriteLine("I am assigned task 2:");
for (int i = 0; i < 50; i++)
{
Console.WriteLine("Task2");
}

handle.Set();
}
public static void Task3(EventWaitHandle waitFor, EventWaitHandle handle)
{
waitFor.WaitOne();

Console.WriteLine("I am assigned task 3:");
for (int i = 0; i < 50; i++)
{
Console.WriteLine("Task3");
}

handle.Set();
}
}

关于c# - 如何在 C# 线程中使用等待句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5538902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com