最近在学习C#线程,整理了所有的开启线程的方法,可供大家参考
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
public delegate int testc(int i);
public static int test_func(int i)
{
Console.WriteLine("Into_test_func "+i);
return 100;
}
class DownLoad
{
string path;
string name;
public DownLoad(string path,string name)
{
this.path = path;
this.name = name;
}
public void DownLoadFile()
{
//真要连接网络的话肯定要连接下载服务器的,这里只是演示下线程代码
Console.WriteLine("Download当前线程ID:"+Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("路径" + path +"文件"+name);
Thread.Sleep(2000);
Console.WriteLine("下载完成");
}
}
static void ThreadPoolTest(object obj)
{
Console.WriteLine("Into ThreadPoolTest ID:"+Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Please Wattting");
Thread. Sleep(2000);
Console.WriteLine("OK");
}
static void TaskTest()
{
Console.WriteLine("任务开始");
Thread.Sleep(2000);
Console.WriteLine("任务结束");
}
//C#开启线程的几种方法
static void Main(string[] args)
{
/*1.通过委托的方式开启线程
testc tete = test_func;
//用于保存结果的变量,通过lambda实现线程完成后的回调
IAsyncResult IAsync = tete.BeginInvoke(666,
(@AsyncResult) => { Console.WriteLine("Into AsyncCallBack" + @AsyncResult.IsCompleted+ tete.EndInvoke(@AsyncResult));},
null);
Console.WriteLine("Main");
Console.ReadKey();*/
/* 2.使用Thread类开起线程
DownLoad downloadClass = new DownLoad("https://www.xxxx.com","_666");
Thread thread = new Thread(downloadClass.DownLoadFile);
thread.Start();
Console.WriteLine("Main线程ID:"+Thread.CurrentThread.ManagedThreadId);*/
/*//3.通过线程池的方法开起线程
ThreadPool.QueueUserWorkItem(ThreadPoolTest);
ThreadPool.QueueUserWorkItem(ThreadPoolTest);
ThreadPool.QueueUserWorkItem(ThreadPoolTest);
Console.WriteLine("Main ID:"+Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();*/
//4.通过任务开起线程
//创建出来的是后台线程,和ThreadPoool有些类似,这里需要注意,如果操作系统检测到没有前台线程,
会关闭进程。
/* Task tesk1 = new Task(TaskTest);
tesk1.Start();
TaskFactory tf = new TaskFactory();
tf.StartNew(TaskTest);
Console.ReadKey();*/
}
}
}