gpt4 book ai didi

c# - 在 while() 循环中使用 ManualResetEvent()

转载 作者:行者123 更新时间:2023-11-30 23:20:23 33 4
gpt4 key购买 nike

我对我的简单代码有疑问:

 public partial class Form1 : Form {

ManualResetEvent ResetEvt = new ManualResetEvent(false);
Thread t1;
public Form1() {
InitializeComponent();
}
//create
private void button1_Click(object sender, EventArgs e) {
t1 = new Thread(new ParameterizedThreadStart((reset) => {
int cont = 0;
var resett = reset as ManualResetEvent;
Thread.CurrentThread.IsBackground = true;
while (resett.WaitOne()) {
try {
this.BeginInvoke(new Action(() => this.richTextBox1.AppendText("Ciao " + cont)));
cont++;
Thread.Sleep(500);
}
catch (Exception) {
MessageBox.Show("END");
}
}
this.BeginInvoke(new Action(() => this.richTextBox1.AppendText("ok finished " + cont)));
}));
}

private void button2_Click(object sender, EventArgs e) {

try {
t1.Start(this.ResetEvt);
}
catch (Exception) {

}
}

private void button3_Click(object sender, EventArgs e) {
this.ResetEvt.Reset();
}

private void button4_Click(object sender, EventArgs e) {
ResetEvt.Set();
}

private void button5_Click(object sender, EventArgs e) {
// ??? ho can stop while? and continue execution?
}

Weel, ManualResetEvent 的使用方法简单明了,但是为什么要排队 this.BeginInvoke(new Action(() => this.richTextBox1.AppendText("ok finished "+ cont))); 永远不会执行?我可以停止我的线程 (.Reset) 并重新启动它 (.Set),但是当 resett.WaitOne() 变为 FALSE 时,为什么我的代码不跳转到 this.BeginInvoke(new Action(() => this. richTextBox1.AppendText("ok 完成 "+ cont)));?

非常感谢。

最佳答案

我不确定我是否能用你的代码看到你想要的,但你可以这样做:

while (!resett.WaitOne(500))
{
}

然后有第三个按钮来停止循环,如下所示:

private void button3_Click(object sender, EventArgs e)
{
ResetEvt.Set();
}

不带参数的 WaitOne() 会阻塞当前线程,直到我设置了处理程序,但带有以毫秒为单位的参数,它会在那之后返回,但只要未设置处理程序,它就会返回 false。

关于c# - 在 while() 循环中使用 ManualResetEvent(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39788843/

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