gpt4 book ai didi

c# - 为什么值变量不改变?

转载 作者:行者123 更新时间:2023-12-03 13:21:27 26 4
gpt4 key购买 nike

我的winForms中有一个Timer,当TimeSpan0时,我将done设置为true,然后尝试检查该值是否是一个线程。

我的代码:

初始变量:

private DateTime endTime = DateTime.UtcNow.AddMinutes(1);
private bool done;
private bool running = true;
private int count = 0;
private delegate void setLabelMethod(string msg);
private void setLabelValue(string msg) { label2.Text = msg; }

计时器处理:
private void timer1_Tick_1(object sender, EventArgs e)
{
TimeSpan remainingTime = endTime - DateTime.UtcNow;

if (remainingTime <= TimeSpan.Zero)
{
label1.Text = "Done!";
timer1.Enabled = false;
done = true;
running = false;
}
else
{
//...
}

}

线程回调函数:
private void test()
{
do
{
if (done)
{
Invoke(new setLabelMethod(setLabelValue), "yeah");
done = false;
}

Thread.Sleep(500);

} while (running);
}

开始 timer1_TickThread执行。
 private void button2_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(test));
th.Start();
timer1.Enabled = true;
}

问题是 .test()方法中的以下语句永远都不是 true,为什么?

语句
 if (done)
{
Invoke(new setLabelMethod(setLabelValue), "yeah");
done = false;
}

有人可以指出我的错误吗?提前致谢。

最佳答案

正如Martin James所提到的,您应该使用而不是轮询标志
线程同步机制。

这个简单的示例说明了如何使用Monitor.WaitMonitor.Pulselock进行此操作。

此代码与您的代码之间的重要区别在于,这将阻止线程运行直到满足条件,从而改善了性能的代码。

class Program
{
static void Main(string[] args)
{
ThreadExample example = new ThreadExample();
Thread thread = new Thread(example.Run);

Console.WriteLine("Main: Starting thread...");
thread.Start();

Console.WriteLine("Press a key to send a pulse");
Console.ReadKey();

lock (example) //locks the object we are using for synchronization
{
Console.WriteLine("Sending pulse...");
Monitor.Pulse(example); //Sends a pulse to the thread
Console.WriteLine("Pulse sent.");
}
thread.Join();

Console.ReadKey();
}
}

class ThreadExample
{
public void Run()
{
Console.WriteLine("Thread: Thread has started");
lock (this) //locks the object we are using for synchronization
{
Monitor.Wait(this); //Waits for one pulse - thread stops running until a pulse has been sent
Console.WriteLine("Thread: Condition has been met");
}
}
}

要修改代码以使用此机制,您需要维护对用于启动线程的对象的引用(在本示例中,我将其称为threadObject)
private void timer1_Tick_1(object sender, EventArgs e)
{
TimeSpan remainingTime = endTime - DateTime.UtcNow;

if (remainingTime <= TimeSpan.Zero)
{
label1.Text = "Done!";
timer1.Enabled = false;
lock(threadObject){
Monitor.Pulse(threadObject); //You signal the thread, indicating that the condition has been met
}
}
else
{
//...
}
}

然后,在test()方法中,您只需要这样做:
private void test()
{
lock(this)
{
Monitor.Wait(this); //Will stop the thread until a pulse has been recieved.
Invoke(new setLabelMethod(setLabelValue), "yeah");
}
}

关于c# - 为什么值变量不改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7973086/

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