简体   繁体   English

运行线程一定时间

[英]Running a thread for a certain amount of time

I have a method that reads my RFID reader with a thread,I want to keep this running for a certain amount of time,then stop it,whats the best way to do this? 我有一种方法可以用线程读取RFID阅读器,我想让它保持运行一定时间,然后停止它,什么是最好的方法?

For example: 例如:

Run: 跑:

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

Run for 5 seconds: 运行5秒:

Stop: 停止:

ReaderAPI.Actions.Inventory.Stop();

Tried stopwatch but it's not threadsafe I think. 尝试过秒表,但我认为它不是线程安全的。

tried this: 尝试了这个:

    {
        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();
    }

System.Threading.Timer will help you to solve the problem System.Threading.Timer将帮助您解决问题

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

here is the stop method 这是停止方法

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

How about, 怎么样,

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

or if your method is not async . 或者您的方法不是async

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

I would caveat this answer, if it is important that 5 second period has a very accurate duration? 如果5秒钟的持续时间很准确很重要,我会警告这个答案。 Task.Delay() and Thread.Sleep() are not appropriate, on their own, for high accuracy timing. Task.Delay()Thread.Sleep()本身不适合用于高精度计时。


Incidentally, Stopwatch has a StartNew factory method so you can do, 顺便说一句, Stopwatch具有StartNew工厂方法,因此您可以

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

You can use Sleep: 您可以使用睡眠:

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

Or compare the elapsed time: 或比较经过的时间:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM