在特定时间段内阻塞线程的精确方法是什么? [英] What is a precise way to block a thread for a specific period of time?

查看:103
本文介绍了在特定时间段内阻塞线程的精确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的系统需要消耗IEnumerable的工作项,遍历每个工作项,并且在它们之间等待一定的时间.我想让枚举站点的系统尽可能简单.也就是说,我希望有一个方法可以在foreach块的末尾调用,该方法将在我指定的特定时间段内阻塞-但我不想使用Thread.Sleep,因为无法保证精度.

The system I'm working on needs to consume an IEnumerable of work items, iterate through each of them, and in between them wait for a certain period of time. I would like to keep the system as simple as possible at the enumeration site. That is, I'd like to have a method that I can call at the end of the foreach block which will block for the specific amount of time I specify - but I don't want to use Thread.Sleep because it's impossible to guarantee precision.

我需要阻塞的最短时间是100毫秒,但是我不希望它阻塞的时间超过此时间,我已经看到Thread.Sleep有时会这样做(我想是因为时间的缘故)在上下文切换器等中使用.

The minimum amount of time I'll need to block for is 100ms, but I don't want it to block any longer than this, which I've seen Thread.Sleep do on occasion (I assume because of the time taken in context switches, etc).

相关;带有超时值的WaitHandle.Wait调用与Thread.Sleep具有相同的作用吗?

Related; does a call to WaitHandle.Wait with a timeout value do the same thing as Thread.Sleep?

推荐答案

为什么在枚举时确实需要等待?

Why exactly do you need to wait while enumarating?

如果IEnumerable集合在您浏览过程中发生更改,您将获得异常,因此,实际上,在您处理线程时,其他线程无法添加或删除任何项目.

If a IEnumerable collection changes while you're going through it you'll get an exception so as a matter of fact no items can be added or removed by other threads while you thread is working on it.

鉴于此,为什么人为地延迟?只需将其消耗掉,然后让调度程序在线程之间分配工作即可.

Given that, why the artificial delay? Just consume it as it comes and let the scheduler distribute the work among your threads.

如果您想要一个非常准确的等待时间,我建议您使用Thread.Sleep(时间-20毫秒),然后忙于等待正确的时间来完成工作.

If you want a really really precise wait time I suggest you use a Thread.Sleep(time - 20 ms) and then busy wait for the right time do your work.

只有实时操作系统才能为您提供这种精度.您可以假设Thread.Sleep的精度约为20毫秒,因此从理论上讲,您可以一直睡到所需的时间-实际时间约为20毫秒,然后旋转20毫秒,但您必须浪费那20毫秒.甚至不能保证您将获得实时结果,调度程序可能只是在即将执行RELEVANT部分时(在旋转之后)将线程移出.

Only real time operating system can give you such precision. You can assume Thread.Sleep has a precision of about 20 ms so you could, in theory sleep until the desired time - the actual time is about 20 ms and THEN spin for 20 ms but you'll have to waste those 20 ms. And even that doesn't guarantee that you'll get real time results, the scheduler might just take your thread out just when it was about to execute the RELEVANT part (just after spinning)

这篇关于在特定时间段内阻塞线程的精确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆