C#关于线程的问题

1、通过System.threading.Thread类可以创建新的线程,并在线程堆栈中运行静态和动态的实例,可以通过Thread类的构造方法传递一个无参数,并且不返回的委托,

  class Program

    {
          public static void myStaticThreadMethod(){
              Console.WriteLine("myStaticThrteadMethod");
            }
          public void myThreadMethod() {
              Console.WriteLine("myThreadMethod");
          }
        static void Main(string[] args)
        {
            Thread thread1 = new Thread(myStaticThreadMethod);
            thread1.Start();//只有调用Start方法,线程才会启用
            //Thread thread1 = new Thread(MyThread);
            Thread thread2 = new Thread(new Program().myThreadMethod);
            thread2.Start();
            Thread thread3 = new Thread(delegate() { Console.WriteLine("niming weituo"); });
            thread3.Start();
            Thread thread4 = new Thread(() => { Console.WriteLine("Lambda biaodashi"); });
            thread4.Start();
            //Console.WriteLine("{0}", thread3.GetHashCode);
            Console.ReadKey();
          
        }
    }

2、定义一个线程类

  

3、Thread 类有一个带参数的委托的重载形式,这个委托定义如下:

     

class NewThread : MyThread 
     private String p1; 
     private int p2; 
     public NewThread(String p1, int p2) 
    
         this .p1 = p1; 
         this .p2 = p2; 
    
  
     override public void run() 
    
         Console.WriteLine(p1); 
         Console.WriteLine(p2); 
    
  
NewThread newThread = new NewThread( "hello world" , 4321 ); 
newThread.start(); 
4、线程计数器
     使用join方法只有在线程结束时候才会执行下面的语句,可以对每一个线程调用join方法,这个调用要在另一个线程中,不能在主线程中,不然会阻塞。
5、通过委托来实现异步调用
     class Program
    {
        static void Main(string[] args)
        {
            String i = "canshu";
            Console.WriteLine("调用异步方法前");
            PostAsync(i);
            Console.WriteLine("调用异步方法后");
            Console.ReadKey();

        }
        delegate void AsyncFoo(String i);
        private static void PostAsync(object i) {
            AsyncFoo caller = Myfucn;
            caller.BeginInvoke(i.ToString(), FooCallBack, caller);

        }
        private static void FooCallBack(IAsyncResult ar) {
            var caller = (AsyncFoo)ar.AsyncState;
            caller.EndInvoke(ar);
        }
        private static void Myfucn(String i) {
            Console.WriteLine("tonguo weituo shixian");
        }
    }
   
 
 

猜你喜欢

转载自www.cnblogs.com/xinxianquan/p/9771835.html