[英]EventWaitHandle blocking the entire form
I've been looking around for quite some time now, but without any solution.. 我已经环顾了很长时间,但没有任何解决方案。
What I want to achieve, is use an EventWaitHandle class in order to pause one thread. 我想要实现的是使用EventWaitHandle类来暂停一个线程。
So, I create two buttons on a form. 因此,我在窗体上创建了两个按钮。 The first one should send a message, then pause, and the second one should unpause the thread of the first button, which then sends another message. 第一个应该发送一条消息,然后暂停,第二个应该取消暂停第一个按钮的线程,然后第一个按钮发送另一个消息。 Like that: 像那样:
using System;
using System.Windows.Forms;
using System.Threading;
namespace Application
{
public partial class Form1 : Form
{
EventWaitHandle wh = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Thread blocked!");
wh.WaitOne();
MessageBox.Show("Thread unblocked!");
}
private void button2_Click(object sender, EventArgs e)
{
wh.Set();
}
}
}
But as soon as the thread gets blocked with the wh.WaitOne()
, I can't do anything on the entire form, including pushing the second button or at least closing it.. 但是,一旦线程被wh.WaitOne()
阻塞,我就无法对整个表单执行任何操作,包括按下第二个按钮或至少关闭它。
What did I do wrong? 我做错了什么? Because I can't seem to find any difference between examples I could find, and my code. 因为我似乎找不到可以找到的示例与代码之间的任何区别。
You have only 1 thread. 您只有1个线程。 The UI thread. UI线程。 When you block it, you block the entire UI. 阻止它时,将阻止整个UI。
You'll have to create a second thread. 您必须创建第二个线程。
Try this: 尝试这个:
private void button1_Click(object sender, EventArgs e)
{
new Thread() {
void run() {
MessageBox.Show("Thread blocked!");
wh.WaitOne();
MessageBox.Show("Thread unblocked!");
}
}.start();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.