zoukankan      html  css  js  c++  java
  • 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");
            }
        }
       
     
     
  • 相关阅读:
    结对项目之需求分析与原型设计
    第二次结对编程作业——毕设导师智能匹配
    历届软工作品、竞赛平台作品调研
    软件工程实践项目课程的自我目标
    Build to win!——获得小黄衫的感想
    VC++智能感知插件 Visual Assist X
    Haproxy+Keepalived高可用环境部署梳理(主主和主从模式)
    安装cronsun管理定时脚本
    四层、七层负载均衡的区别
    使用LVS实现负载均衡原理及安装配置详解
  • 原文地址:https://www.cnblogs.com/xinxianquan/p/9771835.html
Copyright © 2011-2022 走看看