运行一段时间的线程

时间:2014-07-23 07:53:08

标签: c#

我有一个用线程读取我的RFID阅读器的方法,我想让它保持运行一段时间,然后停止它,最好的方法是什么?

例如:

生成

ReaderAPI.Actions.Inventory.Perform(null, null, antennainfo);

运行5秒钟:

停止:

ReaderAPI.Actions.Inventory.Stop();

尝试过秒表,但我认为这不是线程安全的。

尝试了这个:

    {
        Stopwatch stopwatch = new Stopwatch();
        TimeSpan RequiredTimeLine = new TimeSpan(0, 0, 0, 5, 0);
        TimeSpan timeGone = new TimeSpan();

        ReaderAPI.Actions.Inventory.Perform(null, null, antennainfo);
        stopwatch.Start();

        while (timeGone.Seconds < RequiredTimeLine.Seconds)
        {
            timeGone = stopwatch.Elapsed;
        }
        stopwatch.Stop();
        ReaderAPI.Actions.Inventory.Stop();
    }

3 个答案:

答案 0 :(得分:2)

System.Threading.Timer将帮助您解决问题

var timer = new Timer(new TimerCallback(StopInventory), null, 5000, Timeout.Infinite);
ReaderAPI.Actions.Inventory.Perform(null, null, antennainfo);

这是停止方法

private void StopInventory(object obj)
{
    ReaderAPI.Actions.Inventory.Stop();
    timer.Change( Timeout.Infinite , Timeout.Infinite ) ;
}

答案 1 :(得分:2)

怎么样,

ReaderAPI.Actions.Inventory.Perform(null, null, antennainfo);
await Task.Delay(5000);
ReaderAPI.Actions.Inventory.Stop();

或者您的方法不是async

ReaderAPI.Actions.Inventory.Perform(null, null, antennainfo);
Task.Delay(5000).Wait();
ReaderAPI.Actions.Inventory.Stop();

如果重要的是5秒钟的持续时间非常准确,我会告诫这个答案吗? Task.Delay()Thread.Sleep()本身并不适合高精度计时。


顺便说一下,Stopwatch有一个StartNew工厂方法,所以你可以这样做,

var stopwatch = Stopwatch.StartNew();
// Thing to time.
stopwatch.Stop();

答案 2 :(得分:0)

您可以使用睡眠:

ReaderAPI.Actions.Inventory.Perform(null, null, antennainfo);
System.Threading.Thread.Sleep(5000);
ReaderAPI.Actions.Inventory.Stop();

或者比较经过的时间:

long ticks = DateTime.Ticks;
while(DateTime.Ticks - ticks < 50000000) // 5 seconds
{
    ReaderAPI.Actions.Inventory.Perform(null, null, antennainfo);
}
ReaderAPI.Actions.Inventory.Stop();
相关问题