.net多线程入门

 

首先我们引入using System.Threading; 

然后我们编写一个方法:

public   static   void  SimpleWorkerThread()
        
{
            
for (int i = 0; ; i++)
            
{
                
try
                
{
                    Console.WriteLine(
"Hello from the worker thread.");
                    
if (i > 1000)
                    
{
                        Thread.CurrentThread.Abort();
                        
return;
                    }

                }

                
catch (Exception e)
                
{
                    Console.WriteLine(e.ToString() 
+ " Exception caught.");
                    Thread.ResetAbort();
                }

            }

        }

接着我们把这个方法改一个字.

public   static   void  SimpleWorkerThread1()
        
{
            
for (int i = 0; ; i++)
            
{
                
try
                
{
                    Console.WriteLine(
"操!");
                    
if (i > 1000)
                    
{
                        Thread.CurrentThread.Abort();
                        
return;
                    }

                }

                
catch (Exception e)
                
{
                    Console.WriteLine(e.ToString() 
+ " Exception caught.");
                    Thread.ResetAbort();
                }

            }

        }

把这两个方法都放到类中去,

然后在Main()方法中添加:

         static   void  Main( string [] args)
        
{
            ThreadStart S1 
= new ThreadStart(SimpleWorkerThread);
            ThreadStart S2 
= new ThreadStart(SimpleWorkerThread1);
            Thread T1 
= new Thread(S1);
            Thread T2 
= new Thread(S2);
            T1.Start();
            T2.Start();
        }

 

运行代码,是不是发现我们就可以一边做正经事一边操了?是不是很爽呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值