在我的控制台应用程序中,同步线程内的事件很困难。
using System;
using System.Threading;
using System.Windows.Forms;
namespace ConsoleApplication1
{
public class Example
{
private static Button _button;
private static readonly EventWaitHandle Ewh = new EventWaitHandle(false, EventResetMode.ManualReset);
private static readonly EventWaitHandle Btn = new EventWaitHandle(false, EventResetMode.ManualReset);
[STAThread]
public static void Main()
{
_button = new Button();
_button.Click += _button_Click;
for (int i = 0; i <= 0x4; i++)
{
var t = new Thread(ThreadProc);
t.Start(i);
}
Console.WriteLine("Press ENTER to release a waiting thread.");
Console.ReadLine();
Ewh.Set();
Console.ReadLine();
}
private static void _button_Click(object sender, EventArgs e)
{
Console.WriteLine(new Random().Next(0x1388));
Thread.Sleep(10);
Btn.Set();
}
public static void ThreadProc(object data)
{
_button.PerformClick();
Btn.WaitOne();
Btn.Reset();
Console.WriteLine("Thread {0} blocks.", data);
Ewh.WaitOne();
Console.WriteLine("Thread {0} exits.", data);
}
}
}
应用程序给出的结果是一些随机数,后面跟着线程块,在发出eventwaihandle信号后,数据线程退出,打印在控制台上。
目的是按照如下方式打印数据,如
*随机数据
线程块随机数据线程块…线程退出
*…
的示例输出1234年线程2块
2345年线程0阻塞
3456年线程1阻塞
…
线程1退出
线程4退出
…
如何在线程内同步线程和事件
这是我的代码。它对Btn使用AutoResetEvent。此外,我看到你正在创建按钮,并从后台线程访问它。我删除了这段代码,而是直接调用ButtonClick方法。结果代码如下:
using System;
using System.Threading;
using System.Windows.Forms;
namespace ConsoleApplication1
{
public class Example
{
private static Button _button;
private static readonly EventWaitHandle Ewh = new EventWaitHandle(true, EventResetMode.ManualReset);
private static readonly EventWaitHandle Btn = new EventWaitHandle(true, EventResetMode.AutoReset);
[STAThread]
public static void Main()
{
Ewh.Reset();
_button = new Button();
_button.Click += _button_Click;
for (int i = 0; i <= 0x4; i++)
new Thread(ThreadProc).Start(i);
Console.WriteLine("Press ENTER to release a waiting thread.");
Console.ReadLine();
Ewh.Set();
Console.ReadLine();
}
private static void _button_Click(object sender, EventArgs e)
{
Console.WriteLine(new Random().Next(0x1388));
Thread.Sleep(10);
}
public static void ThreadProc(object data)
{
Btn.WaitOne();
Console.WriteLine("Thread {0} blocks.", data);
_button.PerformClick();
Btn.Set();
Ewh.WaitOne();
Console.WriteLine("Thread {0} exits.", data);
}
}
}
请使用任务调度程序和同步上下文。在主线程中创建一个同步上下文,并将其传递给要在主线程中执行的任务。