C# System.Threading.Timer如何停止
usingSystem;usingSystem.Threading;namespaceReminder{publicclassReminder{publicTimerst...
using System;
using System.Threading;
namespace Reminder
{
public class Reminder
{
public Timer stateTimer;
public void Check()
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecher = new StatusChecker();
TimerCallback tcb = statusChecher.CheckInventory;
stateTimer = new Timer(tcb, autoEvent, 1000, 5000);
//autoEvent.WaitOne(1, false);
stateTimer.Change(5000, 1000);
stateTimer.Dispose();
}
}
class StatusChecker
{
public void CheckInventory(object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
int inventoryShortageCount = 5;
if (inventoryShortageCount > 0)
{
System.Windows.Forms.MessageBox.Show("");
}
}
}
}
在Form里面调用
private void Form1_Load(object sender, EventArgs e)
{
Reminder r = new Reminder();
r.Check();
//r.stateTimer.Dispose();
//如果这样,Timer就直接被Dispose掉了,如何才能在Form里面随意停止Timer
}
autoEvent.WaitOne(1, false);
stateTimer.Change(5000, 1000);
stateTimer.Dispose();
这三条后来测试用的,不是原来代码 展开
using System.Threading;
namespace Reminder
{
public class Reminder
{
public Timer stateTimer;
public void Check()
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecher = new StatusChecker();
TimerCallback tcb = statusChecher.CheckInventory;
stateTimer = new Timer(tcb, autoEvent, 1000, 5000);
//autoEvent.WaitOne(1, false);
stateTimer.Change(5000, 1000);
stateTimer.Dispose();
}
}
class StatusChecker
{
public void CheckInventory(object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
int inventoryShortageCount = 5;
if (inventoryShortageCount > 0)
{
System.Windows.Forms.MessageBox.Show("");
}
}
}
}
在Form里面调用
private void Form1_Load(object sender, EventArgs e)
{
Reminder r = new Reminder();
r.Check();
//r.stateTimer.Dispose();
//如果这样,Timer就直接被Dispose掉了,如何才能在Form里面随意停止Timer
}
autoEvent.WaitOne(1, false);
stateTimer.Change(5000, 1000);
stateTimer.Dispose();
这三条后来测试用的,不是原来代码 展开
6个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询