【发布时间】:2015-10-29 00:30:12
【问题描述】:
我有一个使用 .NET Compact Framework 3.5 的 C# 应用程序,它根据用户交互打开多个表单。在一种特定的形式中,我有一个后台线程,它定期检查运行应用程序的 Windows CE 设备的电池寿命。注意,这不是Main() 中调用的形式。比如Application.Run(new MyOtherForm());在Main()中被调用。
public MyForm()
{
Thread mythread = new Thread(checkBatteryLife);
mythread.IsBackground = true;
mythread.Start();
}
private void checkBatteryLife()
{
while(true)
{
// Get battery life
Thread.Sleep(1000);
}
}
我的问题是,当MyForm 关闭时,后台线程是否也会停止?还是会在应用程序存在时停止(当Main() 完成处理时)?如果后台线程在应用程序关闭时结束,我找到了this 解决方法,但如果线程在窗体关闭时停止,则似乎没有必要。
编辑:我选择使用System.Threading.Timer 而不是Thread。
private System.Threading.Timer batteryLifeTimer;
public MyForm()
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
TimerCallback tcb = checkBatteryLife;
this.batteryLifeTimer = new System.Threading.Timer(tcb, autoEvent, 1000, 10000);
}
private void checkBatteryLife(Object stateInfo)
{
// Get battery life.
// Update UI if battery life percent changed.
}
private void MyForm_Closing(object sender, CancelEventArgs e)
{
this.batteryLifeTimer.Dispose();
}
【问题讨论】:
-
你为什么选择使用线程而不是计时器来完成这样的事情?
-
我想这将取决于检查电池的强度 - 如果这是一个阻塞任务,那么我可以看到在后台线程中处理它的原因。我本来希望线程在表单被处理之前一直运行 - 并且当进程执行时线程肯定会停止 - 没有进程来托管它......
-
@MartinMilan 运行多长时间不会改变它属于
Timer。它最多会确定您使用哪种类型的Timer。 -
Sorry Servy(我会很高兴地服从他...) - 我的想法是防止操作阻塞 UI 线程 - 应该考虑使用 System.Timers.Timer...
标签: c# multithreading windows-ce