WP7 应用程序中的 DispatcherTimer 行为
我正在为 WP7 编写一个录音应用程序。我的 ViewModel 类中有一个 DispatcherTimer 对象,当录制发生时,它会计算经过的秒数以向用户显示录制的长度。我的应用程序存在以下问题:
DispatcherTimer 的刻度间隔设置为一秒 (1000) 毫秒。
当我按下开始按钮时,DispatcherTimer 启动。 当我按下停止按钮时,DispatcherTimers 线程退出。 (一秒钟!,我以为我不想这样))
如果我在快速按下停止按钮后按下开始按钮(中间不到一秒),我的 DispatcherTimer 将无法再次启动,因为它还没有启动还没有停止。 (它的线程还没有退出)
基本上,我最关心的是为什么 DispatcherTimer 必须等到它的滴答时间,才能意识到它已经停止,并且它创建的执行滴答的线程必须退出?
我该如何解决这个问题?谢谢。
I am writing an audio recording application for WP7. I have a DispatcherTimer object in my ViewModel class, that when the recording is happening, counts the elapsed seconds to show the length of the recording to a user. I have the following problem with the app:
The tick interval for the DispatcherTimer is set to one second (1000) ms.
When I press the start button, the DispatcherTimer starts.
When I press the stop button, the DispatcherTimers thread exits. (in a second!, thought I didn't intend it to be that way))
If I do press the start button after pressing stop to swiftly (less then a second inbetween), my DispatcherTimer fails to start again, since it hasn't yet stopped. (it's thread hasn't exited)
Basically, my biggest concern is why does DispatcherTimer has to wait until it's time for its tick, to realize that it has been stopped, and the thread it created to perform ticks in has to exit?
How can I work around this problem? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DispatcherTimers 不保证在时间间隔发生时准确执行,但保证在时间间隔发生之前不执行。这是因为 DispatcherTimer 操作像其他操作一样被放置在 DispatcherTimer 队列上。 DispatcherTimer 操作何时执行取决于队列中的其他作业及其优先级。
参考: http:// msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer(v=VS.95).aspx
您最好使用
System.Threading.Timer
,这是一个在单独线程上触发的计时器类。这对于纯数字计时很有用,在这种情况下您不会尝试更新 UI 等。DispatcherTimers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the DispatcherTimer queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.
Reference: http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer(v=VS.95).aspx
You should better use a
System.Threading.Timer
, which is a timer class that fires on a separate thread. This is good for purely numerical timing, where you're not trying to update the UI, etc.