当前位置: 移动技术网 > IT编程>开发语言>.net > C#开启线程的四种示例

C#开启线程的四种示例

2020年10月13日  | 移动技术网IT编程  | 我要评论
1.异步委托开启线程public class program { public static void main(string[] args) { action<int,

1.异步委托开启线程

public class program
  {
    public static void main(string[] args)
    {
      action<int, int> a = add;
      a.begininvoke(3, 4, null, null);
      console.writeline("执行线程");
      console.readkey();
    }
    static void add(int a, int b)
    {
      console.writeline(a + b);
    }
  }

2.通过thread类开启线程

public class program
  {
    public static void main(string[] args)
    {
      thread t1;
      thread t2;
      t1 = new thread(setinfo1);
      t2 = new thread(setinfo2);
      t1.start();
      //线程睡眠
      //t1.join(1000);
      //挂起线程
      t1.suspend();
      //继续执行线程
      t1.resume();
      //结束线程
      //t1.abort();
 
      t2.start();
      console.readkey();
    }
    //奇数线程
    public static void setinfo1()
    {
      for (int i = 0; i < 100; i++)
      {
        if (i % 2 != 0)
        {
          console.writeline("奇数为" + i);
        }
      }
    }
    //偶数线程
    public static void setinfo2()
    {
      for (int i = 0; i < 100; i++)
      {
        if (i % 2 == 0)
        {
          console.writeline("偶数为" + i);
        }
      }
    }
  }

3.通过线程池开启线程

//线程池可以看做容纳线程的容器;一个应用程序最多只能有一个线程池;threadpool静态类通过queueuserworkitem()方法将工作函数排入线程池;每排入一个工作函数,就相当于请求创建一个线程;
  //线程池的作用:
  //1、线程池是为突然大量爆发的线程设计的,通过有限的几个固定线程为大量的操作服务,减少了创建和销毁线程所需的时间,从而提高效率。
  //2、如果一个线程的时间非常长,就没必要用线程池了(不是不能作长时间操作,而是不宜。),况且我们还不能控制线程池中线程的开始、挂起、和中止
  public class program
  {
    public static void main(string[] args)
    {
      threadpool.queueuserworkitem(new waitcallback(testthreadpool), new string[] { "hjh" });
      console.readkey();
    }
    public static void testthreadpool(object state)
    {
      string[] arry = state as string[];//传过来的参数值
      int workerthreads = 0;
      int completionportthreads = 0;
      threadpool.getmaxthreads(out workerthreads, out completionportthreads);
      console.writeline(datetime.now.tostring() + "---" + arry[0] + "--workerthreads=" + workerthreads + "--completionportthreads" + completionportthreads);
    }
  }

4.通过任务task开启线程

public class program
  {
    public static void main(string[] args)
    {
      task task = new task(downloadfile_my);
      task.start();
      console.readkey();
    }
    static void downloadfile_my()
    {
      console.writeline("开始下载...线程id:"+thread.currentthread.managedthreadid);
      thread.sleep(500);
      console.writeline("下载完成!");
    }
  }

以上就是c#开启线程的四种方法汇总的详细内容,更多关于c#开启线程的资料请关注移动技术网其它相关文章!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网