C#里的多线程,一网打尽thread,task,parallel
C#里的多线程,一网打尽
1.Sync await
2.Thread
3.Threadpool
4.Task
5.Parallel
1.控制线程数量为3,卡界面
ParallelOptions options =new ParalelOptons();
options.MaxDEGREEOfParallelism=3;
Parallel.For(0,10,options,i=>this.Dosomething()); //控制线程数量为3
pageDataList.AsParallel()
.WithDegreeOfParallelism(3) //控制线程数量为3
.ForAll(m =>
2. 不控制线程数量
Parallel.For(0,10,i=>this.Dosomething()); //不控制线程数量
3.控制线程数量为3,不卡界面,主线程不参入计算
Task.Run(()=>{
ParallelOptions options =new ParalelOptons();
options.MaxDEGREEOfParallelism=3;
Parallel.For(0,10,options,i=>this.Dosomething()); //控制线程数量为3,不卡界面,主线程不参入计算
}
4.抓取异常
List<Task> taskList=new List<Task>();
for(int i=0;i<0;i++){
taskList.Add(Task.Run(()=>
{
//dosomething Thread.CurrentThread.ManagedThreadId.ToString("00")
}
}
Task.WaitAll(taskList.ToArray());
5. 线程停止,当有一个线程有异常,停止所有的线程,全局变量isok
CancellationTokenSource cts=new CancellationTokenSource ();
Task.Run(()=>{
if(! cts.IsCancellationRequested)
{
//dosomething
}else{
throw new AggregateException(); //停止了线程
//失败了
}
}
多线程
1.多线程的定义,并行(多个cpu同时执行),并发(CPU分片执行交并发)
2.多线程的执行顺序控制:回调,iscomplate等待,waitOne等待,EndInvoke
3.线程api使用
Thread thread=new Thread(method);
thread.Start(); 开启线程,执行委托的内容
thread.Suspend();
4.线程定制扩展--回调
5.线程池:不用反复创建和销毁代价高,用一个池子保存对象,节约资源,防止滥用不可控
6.线程销毁:Abort() 方法用于销毁线程
Task task=new Task(()=>{
});
task.Start();
Task task =Task.Run(()=>{
};
TaskFactory taskf=new taskFactory();
TaskFactory taskf=Task.Facotry;
taskf.StartNew();
1.控制线程数量为3,卡界面ParallelOptions options =new ParalelOptons();options.MaxDEGREEOfParallelism=3;
Parallel.For(0,10,options,i=>this.Dosomething()); //控制线程数量为3
2. 不控制线程数量Parallel.For(0,10,i=>this.Dosomething()); //不控制线程数量
3.控制线程数量为3,不卡界面,主线程不参入计算Task.Run(()=>{
ParallelOptions options =new ParalelOptons();options.MaxDEGREEOfParallelism=3;Parallel.For(0,10,options,i=>this.Dosomething()); //控制线程数量为3,不卡界面,主线程不参入计算}
4.抓取异常
List<Task> taskList=new List<Task>();for(int i=0;i<0;i++){ taskList.Add(Task.Run(()=> { //dosomething Thread.CurrentThread.ManagedThreadId.ToString("00") }}Task.WaitAll(taskList.ToArray());
5. 线程停止,当有一个线程有异常,停止所有的线程,全局变量isok CancellationTokenSource cts=new CancellationTokenSource (); Task.Run(()=>{
if(! cts.IsCancellationRequested) { //dosomething }else{ throw new AggregateException(); //停止了线程 //失败了 }}