zoukankan      html  css  js  c++  java
  • 多线程开启的三种方式

    第一种《通过委托》

    class Program
    {
    static int Test(int i)
    {
    Console.WriteLine("test"+i);
    return 100;
    Thread.Sleep(10); //让当前线程休眠(暂停当前线程的执行)单位为毫秒ms
    }

    static void Main(string[] args) //在main方法中执行 一个线程的执行是从上往下执行的
    {
    //通过委托来开启一个线程
    //Func<int,int> a = Test;

    //IAsyncResult ar = a.BeginInvoke(100,null,null); //开启一个新的线程去执行A所应用的方法
    ////IAsyncResult类型可以返回当前线程的一种状态

    //Console.WriteLine("main");
    ////while (ar.IsCompleted==false)//如果当前线程没有执行完毕的时候
    ////{
    //// Console.WriteLine(".");

    ////}
    ////int res = a.EndInvoke(ar);//取得异步线程的返回值
    ////Console.WriteLine(res);

    ////检测线程结束

    //bool isEnd = ar.AsyncWaitHandle.WaitOne(1000); //1000毫秒表示超时,如果等待了1000毫秒线程还没有结束的话那么这个方法会返回false 如果在1000毫秒以内线程结束了会返回true

    //if (isEnd)
    //{
    // Console.WriteLine("这个线程结束了");
    // int res = a.EndInvoke(ar);
    // Console.WriteLine(res);
    //}

    //通过回调 检测线程结束
    Func<int,int> a = Test;
    //倒数第二个参数是一个委托类型的参数,表示回调函数,就是当线程结束的时候这个委托参数就会调用这个回调方法
    //IAsyncResult ar = a.BeginInvoke(100,OnCallBack, a); //开启线程调用方法

    a.BeginInvoke(100,ar=>
    {
    int res = a.EndInvoke(ar);
    Console.WriteLine(res);
    },null);

    Console.ReadKey();

    }

    static void OnCallBack(IAsyncResult ar) //这个是第三个参数调用的方式
    {
    Console.WriteLine("线程END");
    Func<int,int> a = ar.AsyncState as Func<int,int>;
    int res = a.EndInvoke(ar);
    Console.WriteLine(res+"这是第三个参数");
    }

  • 相关阅读:
    vue 实现背景图片动态绑定
    开发过程中常用英文单词备忘
    IDEA常用快捷备忘
    Spring-Boot学习纪要-8:Spring-Boot自定义starters
    Spring-Boot学习纪要-7:Spring-Boot启动配置原理
    Spring-Boot学习纪要-0:Spring-Boo与数据访问
    Spring-Boot学习纪要-5:Spring-Boot与Docker
    Spring-Boot学习纪要-4:Spring-Boot与Web开发
    Spring-Boot学习纪要-3:Spring-Boot与日志
    Spring-Boot学习纪要-1:Spring-Boot入门
  • 原文地址:https://www.cnblogs.com/ylllove/p/6809690.html
Copyright © 2011-2022 走看看