首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

System.Timers.timer window服务 怎么单线程计时?

2012-04-23 
System.Timers.timer window服务 如何单线程计时???System.Timers.timer 这个会引发多线程并发,我需要它监

System.Timers.timer window服务 如何单线程计时???
System.Timers.timer 这个会引发多线程并发,我需要它监督某某时间发邮件,它发了n份,如何控制这个Timer多线程????

[解决办法]
那就自己写单线程或者某一时间只能单线程访问的事件加锁
[解决办法]
这是个演示的例子,多线程定时循环向queue中添加消息,timer定时从queue取出消息。

C# code
        static void Main(string[] args)        {            List<Thread> threadlist = new List<Thread>();            for (int i = 0; i < 5; i++)            {                Thread th = new Thread(new ParameterizedThreadStart(Func));                threadlist.Add(th);            }            isStop = false;            for (int i = 0; i < threadlist.Count; i++)            {                threadlist[i].Start(i);                Console.WriteLine("线程"+i.ToString()+"已经启动...");            }            Timer timer = new Timer(new TimerCallback(timerFun),null,0,1000);        }        static bool isStop = true;        static Queue<string> queue = new Queue<string>();        static void Func(object obj)        {            int index = (int)obj;            while (!isStop)            {                lock (queue)                {                    queue.Enqueue("现在时间" + DateTime.Now.ToString());                }                Thread.Sleep(1000);            }        }        static void timerFun(object obj)        {            lock (queue)            {                if (queue.Count > 0)                {                    string s = queue.Dequeue();                    Console.WriteLine("取出消息:" + s);                }            }        } 

热点排行