计时器和锁定 [英] Timers and Locking

查看:95
本文介绍了计时器和锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我在这里缺少一些基本的东西,希望有人可以帮助我.有人可以向我解释为什么在给定以下代码的情况下,向控制台写入的行数超过了?

Hi there,

I am missing something pretty basic here and was hoping someone could help me along.  Can someone explain to me why more than line is written to the console given the code below?

<身体>
使用系统;
使用System.Threading;
命名空间LockME {
类程序{
专用静态计时器_timer;
私有静态对象 _ syncLock = object();
静态void Main(string [] args){
_ timer = <字体样式="color:blue">新 计时器(新的TimerCallback(OnTimerElapsed));
_timer.Change(0,100);
,而(true){
ConsoleKeyInfo x == 控制台 .ReadKey(true);
( x.Key == ConsoleKey.X)
损坏;
Thread.Sleep(5000);
私有静态void OnTimerElapsed(对象状态){
如果是(Monitor.TryEnter(_syncLock)){
}
}
using System;  
using System.Threading;  
 
namespace LockME {  
    class Program {  
        private static Timer   _timer;  
        private static object  _syncLock = new object();  
 
        static void Main(string[] args) {  
            _timer = new Timer(new TimerCallback(OnTimerElapsed));  
            _timer.Change(0, 100);  
 
            while (true) {  
                ConsoleKeyInfo x = Console.ReadKey(true);  
                if (x.Key == ConsoleKey.X)  
                    break;  
 
                Thread.Sleep(5000);  
            }  
        }  
 
        private static void OnTimerElapsed(object state) {  
            if (Monitor.TryEnter(_syncLock)) {  
                Console.WriteLine(DateTime.Now + " : " + Thread.CurrentThread.ManagedThreadId);  
            }  
        }  
    }  
}  
 

推荐答案

来自System.Threading.Timer的文档:

该方法不会在创建计时器的线程上执行;它在系统提供的 ThreadPool 线程上执行.

休眠主线程对计时器线程没有影响.

From the documentation on System.Threading.Timer:

The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

Sleeping the main thread has no effect on the timer thread.


这篇关于计时器和锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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