先打开一个定时器,循环对串口发出代码。当有事件来时暂停定时器,事件结束后再启动定时器。也就是事件执行的过程中挂起定时器。请问大侠们如何挂起定时器。我使用的是 System.Timers.Timer Timer9= new System.Timers.Timer();中的定时器。
解决方案 »
- 在winform中怎样调用html里的js函数
- C#如何实现文件上传?我的ftp服务器用的是SSH?
- [散分,散分]在FreeBSD上安装MonoDevlop成功,mono2.5可用了
- windows服务异常如何处理?
- List<int> a = new List<int>(),将a赋值后,执行List<int> b = new List<int>(),b = a。当我删除b中的元素时,a中的元素也自动被删除,如何解
- 在使用msn模块时出现这样的错误,请问可能是什么原因
- 求解一查询问题,谢谢
- RichTextBox中怎么插入表格??
- 如何在C#中使用API(WritePrivateProfileString)向UTF-8的Ini文件中写入正确的值
- 请问哪位高手知道用程序分配文件夹和文件的权限.(用VB.net或C#)
- .net 大型项目打包问题
- 当我在第一个窗口中打开第二个窗口进行操作时如何才能访问到第一个窗口?
Timer9.Stop() 停止引发 Elapsed 事件。
stop()不能说是挂起定时器,只能停止定时器引发Elapsed事件,不会中断触发事件里已开始执行的代码。
如果我会用以下方法处理,可能效率不高,见笑了。public class Timer1
{
// 标记串口是否被占用
bool m_bIsOccu = false; // 定时器
System.Timers.Timer aTimer; public static void Main()
{
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine(); // Keep the timer alive until the end of Main.
GC.KeepAlive(aTimer);
}
// 定时器对串口发出代码函数
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// 标记串口被占用
m_bIsOccu = true; // 替换为你自己的发送代码
Console.WriteLine("Hello World!"); // 恢复串口标记
m_bIsOccu = false;
} private void OtherEvent()
{
// 停止定时器
aTimer.Stop();
// 等待串口资源释放
while(m_bIsOccu)
{
Thread.Sleep(100);
} // 你的事件处理函数
.... // 重新启动定时器
aTimer.Start();
}
}
{
// 标记串口是否被占用
bool m_bIsOccu = false; // 定时器
System.Timers.Timer aTimer; // 锁
object theLock = new object(); public static void Main()
{
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine(); // Keep the timer alive until the end of Main.
GC.KeepAlive(aTimer);
}
// 定时器对串口发出代码函数
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
lock(theLock)
{
// 替换为您自己的发送代码
Console.WriteLine("Hello World!");
}
} private void OtherEvent()
{
lock(theLock)
{ // 您的事件处理函数
....
}
}