在一段时间内执行功能,并将经过的时间作为参数

时间:2019-02-14 13:42:09

标签: c# multithreading timer

我想在几秒钟内执行一些操作,并将经过的时间作为参数(具体来说,是为外部硬件设备保留配置的值)。实现这一目标的直接方法是什么?在C#可以执行线程和计时器的所有方式中,我有些失落。

到目前为止,这是我所拥有的,但是似乎很笨拙,并且可能是错误的。

System.Threading.Tasks.Task.Run(async () =>
{
    var timeToRun = 5000; // in milliseconds
    var timer = new System.Timers.Timer();
    var startTime = DateTime.Now;
    timer.Elapsed += (s, e) =>
    {
        var elapsedTime = e.SignalTime - startTime;
        var normalizedTime = elapsedTime.TotalMilliseconds / timeToRun;
        someValue = Lerp(from, to, normalizedTime);
    };
    timer.Start();
    await System.Threading.Tasks.Task.Delay(timeToRun);
    timer.Stop();
});

1 个答案:

答案 0 :(得分:1)

我会使用异步方法进行简单的操作:

async Task Loop(int timeInMs, int iterationTimeInMs)
{
    for (int current = 0; current < timeInMs; current += iterationTimeInMs)
    {
        await Task.Delay(iterationTimeInMs);
        var normalizedTime = current / (double)timeInMs;
        someValue = Lerp(from, to, normalizedTime);
    }
}

如果您的Lerp需要花费很长时间,那么

async Task Loop(int timeInMs, int iterationTimeInMs)
{
    Task taskFromLastIteration = null;
    for (int current = 0; current < timeInMs; current += iterationTimeInMs);
    {            
        var delay = Task.Delay(iterationTimeInMs); // start delay now
        if (taskFromLastIteration != null)
            someValue = await taskFromLastIteration;
        await delay;
        var normalizedTime = current / (double)timeInMs;
        taskFromLastIteration = Task.Run(() => Lerp(from, to, normalizedTime));
    }
    if (taskFromLastIteration != null)
        someValue = await taskFromLastIteration;
}