c#实现每隔一段时间执行代码(多线程)
方法一:调用线程执行方法,在方法中实现死循环,每个循环Sleep设定时间;
方法二:使用System.Timers.Timer类;
方法三:使用System.Threading.Timer;
using System; using System.Collections; using System.Threading; public class Test { public static void Main() { Test obj = new Test(); Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString()); //方法一:调用线程执行方法,在方法中实现死循环,每个循环Sleep设定时间 Thread thread = new Thread(new ThreadStart(obj.Method1)); thread.Start(); //方法二:使用System.Timers.Timer类 System.Timers.Timer t = new System.Timers.Timer(100);//实例化Timer类,设置时间间隔 t.Elapsed += new System.Timers.ElapsedEventHandler(obj.Method2);//到达时间的时候执行事件 t.AutoReset = true;//设置是执行一次(false)还是一直执行(true) t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件 while (true) { Console.WriteLine("test_" + Thread.CurrentThread.ManagedThreadId.ToString()); Thread.Sleep(100); } //方法三:使用System.Threading.Timer //Timer构造函数参数说明: //Callback:一个 TimerCallback 委托,表示要执行的方法。 //State:一个包含回调方法要使用的信息的对象,或者为空引用(Visual Basic 中为 Nothing)。 //dueTime:调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。 //Period:调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。 System.Threading.Timer threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(obj.Method3), null, 0, 100); while (true) { Console.WriteLine("test_" + Thread.CurrentThread.ManagedThreadId.ToString()); Thread.Sleep(100); } Console.ReadLine(); } void Method1() { while (true) { Console.WriteLine(DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString()); Thread.CurrentThread.Join(100);//阻止设定时间 } } void Method2(object source, System.Timers.ElapsedEventArgs e) { Console.WriteLine(DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString()); } void Method3(Object state) { Console.WriteLine(DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString()); } }
个人测试实例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Test001 { public class Test { public static void Main(string[] args) { Test obj = new Test(); #region 方法一:调用线程执行方法,在方法中实现死循环,每个循环Sleep设定时间 ////方法一:调用线程执行方法,在方法中实现死循环,每个循环Sleep设定时间 ////Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString()); //打印当前线程ID //Thread thread = new Thread(new ThreadStart(obj.Method1)); //thread.Start(); #endregion #region 方法二:使用System.Timers.Timer类 ////方法二:使用System.Timers.Timer类 //System.Timers.Timer t = new System.Timers.Timer(1000 * 10);//实例化Timer类,设置时间间隔 //t.Elapsed += new System.Timers.ElapsedEventHandler(obj.Method2);//到达时间的时候执行事件 //t.AutoReset = true;//设置是执行一次(false)还是一直执行(true) //t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件 //while (true) //{ // // Console.WriteLine("test_" + Thread.CurrentThread.ManagedThreadId.ToString()); // Thread.Sleep(1000); //} #endregion #region 方法三:使用System.Threading.Timer //方法三:使用System.Threading.Timer //Timer构造函数参数说明: //Callback:一个 TimerCallback 委托,表示要执行的方法。 //State:一个包含回调方法要使用的信息的对象,或者为空引用(Visual Basic 中为 Nothing)。 //dueTime:调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。 //Period:调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。 System.Threading.Timer threadTimer1 = new System.Threading.Timer(new System.Threading.TimerCallback(obj.Method3), null, 0, 1000 * 10); //while (true) //{ // //Console.WriteLine("test_" + Thread.CurrentThread.ManagedThreadId.ToString()); // Thread.Sleep(1000); //} System.Threading.Timer threadTimer2 = new System.Threading.Timer(new System.Threading.TimerCallback(obj.Method4), null, 0, 1000); while (true) { //Console.WriteLine("test_" + Thread.CurrentThread.ManagedThreadId.ToString()); Thread.Sleep(1000); } #endregion #region c#(asp.net) 多线程示例,用于同时处理多个任务 //Thread Thread1 = new Thread(new ThreadStart(CalcSum)); //Thread Thread2 = new Thread(new ThreadStart(CalcGap)); //Thread1.Start(); //Thread2.Start(); //Thread1.Join(); //Thread2.Join(); //Console.ReadLine(); #endregion } #region /// <summary> /// Method1 /// </summary> void Method1() { while (true) { #region 写log日志 string filename = "F:\\ThreadTest1.txt"; //txt文件路径 bool flag = false; //标记是否是新建文件的标量 if (!System.IO.File.Exists(filename)) //如果文件不存在,就新建该文件 { flag = true; System.IO.StreamWriter sr = System.IO.File.CreateText(filename); sr.Close(); } //向文件写入内容 System.IO.StreamWriter x = new System.IO.StreamWriter(filename, true, System.Text.Encoding.Default); if (flag) x.Write("测试开始:" + "\r\n"); x.WriteLine(DateTime.Now.ToString() + "\r\n"); x.Close(); #endregion Console.WriteLine(DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString()); Thread.CurrentThread.Join(1000);//阻止设定时间 } } /// <summary> /// Method2 /// </summary> /// <param name="source"></param> /// <param name="e"></param> void Method2(object source, System.Timers.ElapsedEventArgs e) { #region 写log日志 string filename = "F:\\ThreadTest2.txt"; //txt文件路径 bool flag = false; //标记是否是新建文件的标量 if (!System.IO.File.Exists(filename)) //如果文件不存在,就新建该文件 { flag = true; System.IO.StreamWriter sr = System.IO.File.CreateText(filename); sr.Close(); } //向文件写入内容 System.IO.StreamWriter x = new System.IO.StreamWriter(filename, true, System.Text.Encoding.Default); if (flag) x.Write("测试开始:" + "\r\n"); x.WriteLine(DateTime.Now.ToString() + "\r\n"); x.Close(); #endregion Console.WriteLine(DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString()); } /// <summary> /// Method3 /// </summary> /// <param name="state"></param> void Method3(Object state) { #region 写log日志 string filename = "F:\\ThreadTest3.txt"; //txt文件路径 bool flag = false; //标记是否是新建文件的标量 if (!System.IO.File.Exists(filename)) //如果文件不存在,就新建该文件 { flag = true; System.IO.StreamWriter sr = System.IO.File.CreateText(filename); sr.Close(); } //向文件写入内容 System.IO.StreamWriter x = new System.IO.StreamWriter(filename, true, System.Text.Encoding.Default); if (flag) x.Write("测试开始:" + "\r\n"); x.WriteLine(DateTime.Now.ToString() + "\r\n"); x.Close(); #endregion Console.WriteLine("Method3___" + DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString()); } /// <summary> /// Method4 /// </summary> /// <param name="state"></param> void Method4(Object state) { #region 写log日志 string filename = "F:\\ThreadTest4.txt"; //txt文件路径 bool flag = false; //标记是否是新建文件的标量 if (!System.IO.File.Exists(filename)) //如果文件不存在,就新建该文件 { flag = true; System.IO.StreamWriter sr = System.IO.File.CreateText(filename); sr.Close(); } //向文件写入内容 System.IO.StreamWriter x = new System.IO.StreamWriter(filename, true, System.Text.Encoding.Default); if (flag) x.Write("测试开始:" + "\r\n"); x.WriteLine(DateTime.Now.ToString() + "\r\n"); x.Close(); #endregion Console.WriteLine("Method4_" + DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString()); } //求和方法 protected static void CalcSum() { #region 写log日志 string filename = "F:\\CalcSum.txt"; //txt文件路径 bool flag = false; //标记是否是新建文件的标量 if (!System.IO.File.Exists(filename)) //如果文件不存在,就新建该文件 { flag = true; System.IO.StreamWriter sr = System.IO.File.CreateText(filename); sr.Close(); } //向文件写入内容 System.IO.StreamWriter x = new System.IO.StreamWriter(filename, true, System.Text.Encoding.Default); if (flag) x.Write("测试开始:" + "\r\n"); x.WriteLine(DateTime.Now.ToString() + "\r\n"); x.Close(); Console.WriteLine(DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString()); System.Threading.Thread.Sleep(5000); #endregion #region //long sum = 0; //for (long i = 0; i < 100; i++) //{ // sum += i; // Response.Write(string.Format("Thread1-->i={0}:sum={1}<br/>", i, sum)); // Response.Flush(); // System.Threading.Thread.Sleep(5000); //} #endregion } //求差方法 protected static void CalcGap() { #region 写log日志 string filename = "F:\\CalcGap.txt"; //txt文件路径 bool flag = false; //标记是否是新建文件的标量 if (!System.IO.File.Exists(filename)) //如果文件不存在,就新建该文件 { flag = true; System.IO.StreamWriter sr = System.IO.File.CreateText(filename); sr.Close(); } //向文件写入内容 System.IO.StreamWriter x = new System.IO.StreamWriter(filename, true, System.Text.Encoding.Default); if (flag) x.Write("测试开始:" + "\r\n"); x.WriteLine(DateTime.Now.ToString() + "\r\n"); x.Close(); Console.WriteLine(DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString()); System.Threading.Thread.Sleep(1000); #endregion #region //long gap = 0; //for (long i = 100; i >= 0; i--) //{ // gap = i - 1; // Response.Write(string.Format("Thread2-->i={0}:gap={1}<br/>", i, gap)); // Response.Flush(); // System.Threading.Thread.Sleep(1000); //} #endregion } #endregion } }