我在C++ / CLI代码中使用计时器System::Timers::Timer
,希望每100毫秒经过一次。但它会在20秒内触发。但是我用C#编写了相同的代码,效果很好。
C++代码:
#include "stdafx.h"
using namespace System;
using namespace System::Timers;
using namespace System::Threading;
static void SysTick(Object^ state, ElapsedEventArgs^ e)
{
DateTime _current = System::DateTime::Now;
String^ dt_str = String::Format("NOW: @{0}.{1:000}", _current.ToLongTimeString(), _current.Millisecond);
Console::WriteLine(dt_str);
}
int main(array<System::String ^> ^args)
{
System::Timers::Timer^ sys_tick = gcnew System::Timers::Timer(100);
sys_tick->BeginInit();
sys_tick->AutoReset = true;
sys_tick->Elapsed += gcnew ElapsedEventHandler(SysTick);
sys_tick->EndInit();
sys_tick->Start();
for (int i = 0; i < 100; i++)
{
Console::WriteLine("[{0}] Main thread sleep 1000 ms", i);
Thread::Sleep(1000);
}
return 0;
}
C#代码:
using System;
using System.Timers;
using System.Threading;
namespace CSharpTimer
{
class Program
{
static void SysTick(object state, ElapsedEventArgs e)
{
DateTime now = DateTime.Now;
Console.WriteLine("NOW: {0}.{1:000}", now.ToLongTimeString(), now.Millisecond);
}
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer(100);
timer.BeginInit();
timer.AutoReset = true;
timer.Elapsed += new ElapsedEventHandler(SysTick);
timer.EndInit();
timer.Start();
for (int i = 0; i < 100; i++)
{
Console.WriteLine("[{0}] Main thread sleep 1000 ms", i);
Thread.Sleep(1000);
}
}
}
}
C++输出:
[0] Main thread sleep 1000 ms
NOW: @5:59:58 PM.284
[1] Main thread sleep 1000 ms
[2] Main thread sleep 1000 ms
[3] Main thread sleep 1000 ms
[4] Main thread sleep 1000 ms
[5] Main thread sleep 1000 ms
[6] Main thread sleep 1000 ms
[7] Main thread sleep 1000 ms
[8] Main thread sleep 1000 ms
[9] Main thread sleep 1000 ms
[10] Main thread sleep 1000 ms
[11] Main thread sleep 1000 ms
[12] Main thread sleep 1000 ms
[13] Main thread sleep 1000 ms
[14] Main thread sleep 1000 ms
[15] Main thread sleep 1000 ms
[16] Main thread sleep 1000 ms
[17] Main thread sleep 1000 ms
[18] Main thread sleep 1000 ms
[19] Main thread sleep 1000 ms
[20] Main thread sleep 1000 ms
NOW: @6:00:18 PM.421
[21] Main thread sleep 1000 ms
[22] Main thread sleep 1000 ms
C#输出:
[0] Main thread sleep 1000 ms
NOW: 6:01:23 PM.032
NOW: 6:01:23 PM.134
NOW: 6:01:23 PM.242
NOW: 6:01:23 PM.352
NOW: 6:01:23 PM.460
NOW: 6:01:23 PM.575
NOW: 6:01:23 PM.682
NOW: 6:01:23 PM.790
NOW: 6:01:23 PM.899
[1] Main thread sleep 1000 ms
NOW: 6:01:24 PM.007
NOW: 6:01:24 PM.122
NOW: 6:01:24 PM.231
NOW: 6:01:24 PM.339
NOW: 6:01:24 PM.447
NOW: 6:01:24 PM.554
NOW: 6:01:24 PM.663
NOW: 6:01:24 PM.780
NOW: 6:01:24 PM.888
[2] Main thread sleep 1000 ms
NOW: 6:01:24 PM.995
NOW: 6:01:25 PM.104
NOW: 6:01:25 PM.212
NOW: 6:01:25 PM.320
最佳答案
是我遇到了这个问题。我的 friend * Filly Hsu *在这里问了这个问题。
投票失败使我的 friend 损失了两分,却没有解决这个奇怪的问题。
我在MSDN上问了同样的问题,几个小时后,一个成员给了我solution:
现在解决了,尽管我仍然不知道为什么。