.NET-多个计时器实例意味着多个线程? [英] .NET - Multiple Timers instances mean Multiple Threads?

查看:81
本文介绍了.NET-多个计时器实例意味着多个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一个运行System.Timers.Timer的Windows服务,该服务可以完成特定工作.但是,我希望某些作品可以同时运行,但使用不同的线程.

I already have a windows service running with a System.Timers.Timer that do a specific work. But, I want some works to run at the same time, but in different threads.

有人告诉我创建一个不同的System.Timers.Timer实例.这样对吗?这样可以并行运行吗?

I've been told to create a different System.Timers.Timer instance. Is this correct? Is this way works running in parallel?

例如:

System.Timers.Timer tmr1 = new System.Timers.Timer();
tmr1.Elapsed += new ElapsedEventHandler(DoWork1);
tmr1.Interval = 5000;

System.Timers.Timer tmr2 = new System.Timers.Timer();
tmr2.Elapsed += new ElapsedEventHandler(DoWork2);
tmr2.Interval = 5000;

tmr1tmr2是否可以在不同的线程上运行,以便DoWork1DoWork2可以同时(即同时运行)运行?

Will tmr1 and tmr2 run on different threads so that DoWork1 and DoWork2 can run at the same time, i.e., concurrently?

谢谢!

推荐答案

这是不正确的.

注意. System.Timers.Timer将为每个Elapsed事件启动一个新线程.当您的Elapsed事件处理程序花费太长时间时,您会遇到麻烦.即使之前的调用尚未完成,您的处理程序也会在另一个线程上再次被调用.这往往会产生难以诊断的错误.您可以通过将AutoReset属性设置为false来避免某些事情.另外,请确保在事件处理程序中使用try/catch,但吞咽了异常而没有诊断.

Be careful. System.Timers.Timer will start a new thread for every Elapsed event. You'll get in trouble when your Elapsed event handler takes too long. Your handler will be called again on another thread, even though the previous call wasn't completed yet. This tends to produce hard to diagnose bugs. Something you can avoid by setting the AutoReset property to false. Also be sure to use try/catch in your event handler, exceptions are swallowed without diagnostic.

这篇关于.NET-多个计时器实例意味着多个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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