C#: class Hello { static void Main()//程序的出口点 { System.Console.Write( "Hello, World!" );//输出Hello, World! } } VB.NET: Module Hello Sub Main() '程序的出口点 System.Console.Write( "Hello, World!" ) '输出Hello, World! End Sub End Module 在编译器上最终生成的都是如下的IL(中间语言)代码: IL_0000: ldstr "Hello, World!" IL_0005: call void [mscorlib]System.Console::Write(string) IL_000a: ret |
public class MyThread { public static void Work() { try { for( int i = 0; i < 4; i++ ) { Console.WriteLine( Thread.CurrentThread.Name + "正在计算" + i.ToString() ); Thread.Sleep( 50 ); } } catch( ThreadAbortException e ) { Console.WriteLine( "错误信息:{0}", e.Message ); Thread.ResetAbort();//取消主线程要求中止的请求,如不执行则ThreadAbortException会在catch块末端再次引发 } Console.WriteLine( Thread.CurrentThread.Name + "完成工作!" ); } } class ThreadAbortTest { public static void { Console.WriteLine( "主线程启动!"); Thread thread = new Thread( new ThreadStart( MyThread.Work ) );//MyThread.Work代表要执行的线程函数,它可以是静态的,也可以是某个类实例的方法,它是要执行的线程函数的委托 thread.Name = "MyThread"; thread.Start();//线程启动后将被CPU调度,但不一定是马上执行,所以同样的例子在不同的机器上可能会有不同的结果。 Console.WriteLine( "主线程第一次休眠!"); Thread.Sleep( 100 ); Console.WriteLine( "MyThread被挂起!"); thread.Suspend();//挂起子线程 Console.WriteLine( "主线程第二次休眠!"); Thread.Sleep( 100 ); Console.WriteLine( "MyThread被恢复!"); thread.Resume();//恢复子线程 thread.Abort();//终止子线程 thread.Join();//直到到子线程完全终止了,主线程才继续运行 Console.WriteLine( "主线程终止!" ); Console.ReadLine(); } } |
lock ( SomeResource ) { //您的处理代码 } 等价于: Monitor.Enter( SomeResource ); try { //您的处理代码 } finally { Monitor.Exit( ); } |
class MonitorSample { private Queue _queue = new Queue(); public void Producer() { int counter = 0; lock( _queue )//判断该资源是否被其他线程占用 { while( counter < 2 ) { Monitor.Wait( _queue );//暂时放弃调用线程对该资源的锁,让Consumer执行 _queue.Enqueue( counter );//生成一个资源 Console.WriteLine( String.Format( "生产:{0}", counter ) ); Monitor.Pulse( _queue );//通知在Wait中阻塞的Consumer线程即将执行 counter++; } } } public void Consumer() { lock( _queue ) { Monitor.Pulse( _queue );//通知在Wait中阻塞的Producer线程即将执行 while( Monitor.Wait( _queue, 10 ) ) { int counter = ( int ) _queue.Dequeue();//取出一个资源 Console.WriteLine( String.Format( "消费:{0}", counter ) ); Monitor.Pulse( _queue );//通知在Wait中阻塞的Producer线程即将执行 } } } static void Main(string[] args) { MonitorSample monitor = new MonitorSample(); Thread producer = new Thread( new ThreadStart( monitor.Producer ) ); Thread consumer = new Thread( new ThreadStart( monitor.Consumer ) ); producer.Start(); consumer.Start(); producer.Join(); consumer.Join(); Console.ReadLine(); } } |
欢迎访问最专业的网吧论坛,无盘论坛,网吧经营,网咖管理,网吧专业论坛
https://bbs.txwb.com
关注天下网吧微信/下载天下网吧APP/天下网吧小程序,一起来超精彩
|
本文来源:vczx 作者:佚名