当前位置: 移动技术网 > IT编程>开发语言>c# > C#开启线程的四种方式示例详解

C#开启线程的四种方式示例详解

2019年07月18日  | 移动技术网IT编程  | 我要评论

一、异步委托开启线程

 public static void main(string[] args){
  action<int,int> a=add;
  a.begininvoke(3,4,null,null);//前两个是add方法的参数,后两个可以为空
  console.writeline("main()");
  console.readkey();
 }
 static void add(int a,int b){
  console.writeline(a+b);
 }

运行结果:

如果不是开启线程,像平常一样调用的话,应该先输出7,再输出main()

二、通过thread类开启线程

    using system;
        using system.threading;
         public static void main(string[] args){
  thread t=new thread(downloadfile_my);//创建了线程还未开启
  t.start("http://abc/def/**.mp4");//用来给函数传递参数,开启线程
  console.writeline("main()");
  console.readkey();
 }
 //thread开启线程要求:该方法参数只能有一个,且是object类型
 static void downloadfile_my(object filepath){
  console.writeline("开始下载:"+filepath);
  thread.sleep(2000);
  console.writeline("下载完成!");
 }

运行结果:

三、通过线程池开启线程

 public static void main(string[] args){
  threadpool.queueuserworkitem(downloadfile_my);
  threadpool.queueuserworkitem(downloadfile_my);
  threadpool.queueuserworkitem(downloadfile_my);
  threadpool.queueuserworkitem(downloadfile_my);
  threadpool.queueuserworkitem(downloadfile_my);
  threadpool.queueuserworkitem(downloadfile_my);
  threadpool.queueuserworkitem(downloadfile_my);
  threadpool.queueuserworkitem(downloadfile_my);
  threadpool.queueuserworkitem(downloadfile_my);
  console.writeline("main()");
  console.readkey();
 }
 static void downloadfile_my(object state){
  console.writeline("开始下载...  线程id:"+thread.currentthread.managedthreadid);
  thread.sleep(2000);
  console.writeline("下载完成!");
 }

运行结果:

4、通过任务开启线程

1>task开启线程

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

运行结果:

2>taskfactory开启线程

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

运行结果:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网