gpt4 book ai didi

c# - 使用 AutoResetEvent 同步两个线程

转载 作者:行者123 更新时间:2023-12-03 01:00:41 25 4
gpt4 key购买 nike

我正在尝试实现AutoResetEvent。为此,我使用一个非常简单的类:

public class MyThreadTest
{
static readonly AutoResetEvent thread1Step = new AutoResetEvent(false);
static readonly AutoResetEvent thread2Step = new AutoResetEvent(false);

void DisplayThread1()
{
while (true)
{
Console.WriteLine("Display Thread 1");

Thread.Sleep(1000);
thread1Step.Set();
thread2Step.WaitOne();
}
}

void DisplayThread2()
{
while (true)
{
Console.WriteLine("Display Thread 2");
Thread.Sleep(1000);
thread2Step.Set();
thread1Step.WaitOne();
}
}

void CreateThreads()
{
// construct two threads for our demonstration;
Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
Thread thread2 = new Thread(new ThreadStart(DisplayThread2));

// start them
thread1.Start();
thread2.Start();
}

public static void Main()
{
MyThreadTest StartMultiThreads = new MyThreadTest();
StartMultiThreads.CreateThreads();
}
}

但这不起作用。这种用法似乎非常简单,所以如果有人能够向我展示问题所在以及我在这里实现的逻辑问题出在哪里,我将不胜感激。

最佳答案

问题不是很清楚,但我猜你希望它显示 1,2,1,2...

然后试试这个:

public class MyThreadTest
{
static readonly AutoResetEvent thread1Step = new AutoResetEvent(false);
static readonly AutoResetEvent thread2Step = new AutoResetEvent(true);

void DisplayThread1()
{
while (true)
{
thread2Step.WaitOne();
Console.WriteLine("Display Thread 1");
Thread.Sleep(1000);
thread1Step.Set();
}
}

void DisplayThread2()
{
while (true)
{
thread1Step.WaitOne();
Console.WriteLine("Display Thread 2");
Thread.Sleep(1000);
thread2Step.Set();
}
}

void CreateThreads()
{
// construct two threads for our demonstration;
Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
Thread thread2 = new Thread(new ThreadStart(DisplayThread2));

// start them
thread1.Start();
thread2.Start();
}

public static void Main()
{
MyThreadTest StartMultiThreads = new MyThreadTest();
StartMultiThreads.CreateThreads();
}
}

关于c# - 使用 AutoResetEvent 同步两个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14481664/

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