C#线程并发执行,自我感觉比较好,用到的地方很多

  using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  System.Threading;

namespace  MyThread
{
    
class  Program
    {
        
private   static   int  newTask( int  ms)
        {
            Console.WriteLine(
" 任务开始 " );
            Thread.Sleep(ms);
            Random random 
=   new  Random();
            
int  n  =  random.Next( 10000 );
            Console.WriteLine(
" 任务完成 " );
            
return  n;
        }

        
private   delegate   int  NewTaskDelegate( int  ms);
             
        
        
static   void  Main( string [] args)
        {
            NewTaskDelegate task 
=  newTask;
            IAsyncResult asyncResult 
=  task.BeginInvoke( 2000 null null );
            while (!asyncResult.AsyncWaitHandle.WaitOne(100false))
            {
                 Console.Write(
"*");              
             }

            //  EndInvoke方法将被阻塞2秒
             int  result  =  task.EndInvoke(asyncResult);           
            Console.WriteLine(result);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/queenpong/article/details/6800316