C# - [ 实践 ] 热水器加热模拟

mac2025-11-13  4

▶ 界面:

▶ 实现(事件 + 多线程):

using System; using System.Threading; using System.Windows.Forms; namespace day1001_Heater { public partial class Form1 : Form { Thread th_process_bar_raise_temperature = null; Thread th_process_bar_down_temperature = null; public delegate void temperature_upto_95(); bool _upto95 = false; bool _is_open = false; public Form1() { InitializeComponent(); temperature_progressBar.Value = 0; //温度判断事件绑定 judgeTemp += ()=> { this.Invoke(new Action(()=>{ show_textbox.AppendText("【注意】: 温度 > 95 !\n"); })); }; judgeTemp += () => { new Thread(() => { MessageBox.Show(" 温度 > 95 !", "【注意】"); }).Start(); }; } //温度判断事件 public delegate void AAA(); public event AAA judgeTemp; public void judgeTemperature() { if (temperature_progressBar.Value >= 95 && !_upto95) { judgeTemp(); _upto95 = true; } else if(temperature_progressBar.Value < 95) { _upto95 = false; } } private void button1_Click(object sender, EventArgs e) { if (!_is_open) { this.Invoke(new Action(() => { show_textbox.AppendText(DateTime.Now+": 开始加热!\n"); })); if (th_process_bar_down_temperature != null) { th_process_bar_down_temperature.Abort(); } this.Invoke(new Action(() => { start_button.Text = "关闭"; })); //进度条开始运行 th_process_bar_raise_temperature = new Thread(() => { for (int i = temperature_progressBar.Value; i < 100; i++) { Thread.Sleep(100); judgeTemperature(); temperature_progressBar.Value = i + 1; psb_percentage.Text = $"{i + 1}℃"; } }); th_process_bar_raise_temperature.Start(); _is_open = true; } else { this.Invoke(new Action(() => { show_textbox.AppendText(DateTime.Now+": 停止加热!\n"); })); th_process_bar_raise_temperature.Abort(); this.Invoke(new Action(() => { start_button.Text = "打开"; })); th_process_bar_down_temperature = new Thread(()=> { for(int i = temperature_progressBar.Value; i > 0; i--) { Thread.Sleep(200); temperature_progressBar.Value = i-1; psb_percentage.Text = $"{i-1}℃"; } }); th_process_bar_down_temperature.Start(); _is_open = false; } } } }

最新回复(0)