本文共 2466 字,大约阅读时间需要 8 分钟。
using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication11 { class Program { public static void Main() { // Create an instance of the Example class, and start two // timers. Program ex = new Program(); ex.StartTimer(2000); ex.StartTimer(1000); Console.WriteLine("Press Enter to end the program."); Console.ReadLine(); } public void StartTimer(int dueTime) { Timer t = new Timer(new TimerCallback(TimerProc)); t.Change(dueTime, 0); } private void TimerProc(object state) { // The state object is the Timer object. Timer t = (Timer)state; t.Dispose(); Console.WriteLine("The timer callback executes."); } /* static void Main(string[] args) { Task t1 = Task.Factory.StartNew(delegate { MyMethod(); }); Task t2 = Task.Factory.StartNew(delegate { MyMethod(); }); Task.WaitAll(t1, t2); Console.WriteLine("主线程代码运行结束"); Console.ReadLine(); } static void MyMethod() { for (int i = 0; i < 5; i++) { Console.WriteLine(DateTime.Now.ToString()); Thread.Sleep(1000); } } */ /* static int[] result = new int[10]; //注意:由于WaitCallback委托的声明带有参数, // 所以将被调用的Fun方法必须带有参数,即:Fun(object obj)。 static void Fun(object obj) { int n = (int)obj; //计算阶乘 int fac = 1; for (int i = 1; i <= n; i++) { fac *= i; } //保存结果 result[n] = fac; } static void Main(string[] args) { //向线程池中排入9个工作线程 for (int i = 1; i <= 9; i++) { //QueueUserWorkItem()方法:将工作任务排入线程池。 ThreadPool.QueueUserWorkItem(new WaitCallback(Fun), i); // Fun 表示要执行的方法(与WaitCallback委托的声明必须一致)。 // i 为传递给Fun方法的参数(obj将接受)。 } //输出计算结果 for (int i = 1; i <= 9; i++) { Console.WriteLine("线程{0}: {0}! = {1}", i, result[i]); } } */ /* public static int count {get;set;} static void Main(string[] args) { count = 100; Thread[] t = new Thread[5]; for (int i = 0; i < 5; i++) { t[i] = new Thread(new ThreadStart(TestMethod)); t[i].Name = i.ToString(); t[i].IsBackground = true; t[i].Start(); } Console.ReadKey(); } public static void TestMethod() { string a= Thread.CurrentThread.Name; //输出线程的名字,线程基本可控了 Console.WriteLine(a); Console.WriteLine(a); } */ /* static void Main(string[] args) { Thread t1 = new Thread(new ThreadStart(TestMethod)); Thread t2 = new Thread(new ParameterizedThreadStart(TestMethod)); t1.IsBackground = true; t2.IsBackground = true; t1.Start(); t2.Start("hello"); Console.ReadKey(); } public static void TestMethod() { Console.WriteLine("不带参数的线程函数"); } public static void TestMethod(object data) { string datastr = data as string; Console.WriteLine("带参数的线程函数,参数为:{0}", datastr); } */ } }转载地址:http://btdaf.baihongyu.com/