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");
        }
    }
   
 
 

转载于:https://www.cnblogs.com/xinxianquan/p/9771835.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值