C# 调度程序的毫秒间隔

C# 调度程序的毫秒间隔,c#,timer,windows-phone,C#,Timer,Windows Phone,我正在使用Dispatcher调用C#中的void: 但是我希望间隔是几毫秒,TimeSpan的参数是小时、分钟、秒,并且只接受整数(据我所知)。调度员有工作安排吗?我尝试了计时器,但无法使用它(显然缺少引用) 提前感谢。TimeSpan对象有一个以毫秒为参数的构造函数: MSDN提供了详细信息: 基本上,用新时间跨度(0,0,0,0,0,0,毫秒超时)替换新时间跨度(0,0,1) counter.Interval = TimeSpan.FromMilliseconds(1); 尽管@EB

我正在使用Dispatcher调用C#中的void:

但是我希望间隔是几毫秒,TimeSpan的参数是小时、分钟、秒,并且只接受整数(据我所知)。调度员有工作安排吗?我尝试了计时器,但无法使用它(显然缺少引用)


提前感谢。

TimeSpan对象有一个以毫秒为参数的构造函数:

MSDN提供了详细信息:

基本上,用
新时间跨度(0,0,0,0,0,0,毫秒超时)
替换
新时间跨度(0,0,1)

  counter.Interval = TimeSpan.FromMilliseconds(1);

尽管@EBrown的答案已经告诉您如何使用
Dispatchermer
的毫秒数,但它的精度应该在15-20毫秒左右,并且每次迭代都会出错,这使得它有点不切实际

但是,可以通过在
调度程序
的同时启动
System.Diagnostics.StopWatch
来解决此问题,并以较小的时间步长检查滴答事件中的
StopWatch.ElapsedMilliskes
,这似乎可以给出更精确的结果。它还与
系统.Timers.Timer
配合使用

下面是一个基于我制作的WPF程序的简短示例

private void StartTimers(object sender, RoutedEventArgs e)
{
    dtimer = new DispatcherTimer();
    dtimer.Tick += new EventHandler(dTimer_Tick);
    dtimer.Interval = TimeSpan.FromMilliseconds(1);  // the small time step

    stopWatch = new StopWatch();

    dTimer.Start();
    stopWatch.Start();
}

private void dTimer_Tick(object sender, EventArgs e)
{        
     currentTime = stopWatch.ElapsedMilliseconds;
        if (currentTime - oldTime > interval)
        {
            oldTime = currentTime;
            DoStuff();
        }
}   

在Tick事件中使用
StopWatch.Restart
进行迭代将产生与
DispatchTimer
相同的错误问题,因为它将在DispatchTimer事件触发时重新启动。

TimeSpan
有一个耗时毫秒的构造函数:。基本上,使用
newtimespan(0,0,0,0,毫秒)@EBrown我想这绝对是一个回答
private void StartTimers(object sender, RoutedEventArgs e)
{
    dtimer = new DispatcherTimer();
    dtimer.Tick += new EventHandler(dTimer_Tick);
    dtimer.Interval = TimeSpan.FromMilliseconds(1);  // the small time step

    stopWatch = new StopWatch();

    dTimer.Start();
    stopWatch.Start();
}

private void dTimer_Tick(object sender, EventArgs e)
{        
     currentTime = stopWatch.ElapsedMilliseconds;
        if (currentTime - oldTime > interval)
        {
            oldTime = currentTime;
            DoStuff();
        }
}