一、C#Timers的区别
C#有3种Timer
1.System.Threading.Timer
2.System.Timers.Timer
3.System.Windows.Forms.Timer
主要区别:System.Threading.Timer和System.Timers.Timer是多线程的,只要时间到了,就会执行。哪怕前一次还没执行完,他还是会开个线程继续执行新的任务。
System.Windows.Forms.Timer是单线程的,只有等前一次执行完了,才会执行第二次的任务。如果间隔5秒执行,如果第一次任务处理超过5秒,那么就会延后第二次任务。
- 类适用于作为基于服务器的使用或在多线程环境; 中的服务组件它没有用户界面并不是在运行时中可见。
- System.Timers.Timer类,此类旨在为基于服务器或服务组件在多线程环境中使用; 它没有用户界面并不是在运行时中可见。
- 该组件没有用户界面,专供在单线程环境中;它在 UI 线程上执行。
使用方法参考:C#-Forms.Timer、Timers.Timer、Threading.Timer的比较和使用
C#实现一个简单的定时任务 System.Timers.Timer
最近用Timer踩了一个坑,分享一下避免别人继续踩 System.Timers.Timer 线程安全
C# 多线程九之Timer类 System.Threading.Timer 线程安全
c# 多线程之-- System.Threading Timer的使用
注:Timers.Timer可为同一回调方法配置多个定时器,第一次执行为声明之后一个间隔,Threading.Timer为相同方法设置定时器时,只要一个定时器使用了 Timeout.Infinite,会导致其他定时器也不能循环执行,可配置第一次执行的时间。
使用委托开启多线程(多线程深入)
1、用委托(Delegate)的BeginInvoke和EndInvoke方法操作线程
BeginInvoke方法可以使用线程异步地执行委托所指向的方法。然后通过EndInvoke方法获得方法的返回值(EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。
class Program { private delegate int NewTaskDelegate(int ms); private static int newTask(int ms) { Console.WriteLine("任务开始"); Thread.Sleep(ms); Random random = new Random(); int n = random.Next(10000); Console.WriteLine("任务完成"); return n; } static void Main(string[] args) { NewTaskDelegate task = newTask; IAsyncResult asyncResult = task.BeginInvoke(2000, null, null); //EndInvoke方法将被阻塞2秒 int result = task.EndInvoke(asyncResult); Console.WriteLine(result); Console.Read(); } }