Thread

来源:互联网 发布:海南网络诈骗最新新闻 编辑:程序博客网 时间:2024/06/17 12:49
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Runtime.Remoting.Messaging;namespace Thread12_1{ class Program { static void sleep(object o, out int r) { r = Int32.Parse(o.ToString()); Console.WriteLine("r = {0}", r); Thread.Sleep(r * 1000); // Console.WriteLine("it sleeps for {0} seconds", n); } delegate void AsnycDelegate(object o, out int r); static void Main(string[] args) { testTwo(); } //12-1 static void testOne() { /* for (int i = 0; i < 10; i++) sleep(); * */ /* for (int i = 0; i < 10; i++) { Random random = new Random(); int n = random.Next(1, 3); Thread t = new Thread(sleep); t.IsBackground = true; t.Start(n); t.Join(); } */ Console.WriteLine("main exit"); } //12-2 static void testTwo() { AsnycDelegate d = new AsnycDelegate(sleep); // for(int i = 0; i < 5;i ++) // { Random random = new Random(); int n = random.Next(1, 5); int r; d.BeginInvoke(n, out r, new AsyncCallback(done), DateTime.Now); // } Console.WriteLine("main goes"); Console.ReadLine(); } static void done(IAsyncResult ar) { Console.WriteLine("done"); AsyncResult result = (AsyncResult)ar; DateTime param = (DateTime)result.AsyncState; AsnycDelegate handler = (AsnycDelegate)result.AsyncDelegate; int r; handler.EndInvoke(out r, result); Console.WriteLine("sleep {0} seconds", r); Console.WriteLine("done exit"); } }}
原创粉丝点击