C# Parallel并发执行相关问题
1、Parallel并发执行
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using System.Configuration;
using System.Collections.Concurrent;
namespace ConsoleApplication57
{
class Program
{
static void Main(string[] args)
{
ParallelDemo BingFa = new ParallelDemo();
BingFa.ParallelInvokemethod();
Console.ReadKey();
BingFa.ParallelForMethod();
Console.ReadKey();
BingFa.ParallelForMethod2();
BingFa.ParallelBreak();
}
}
public class ParallelDemo {
private Stopwatch stopWatch = new Stopwatch();
public void Run1() {
Thread.Sleep(2000);
Console.WriteLine("Task 1 is cost 2 sec");
}
public void Run2() {
Thread.Sleep(3000);
Console.WriteLine("Task 2 is cost 3 sec");
}
public void ParallelInvokemethod() {
stopWatch.Start();
Parallel.Invoke(Run1, Run2);
stopWatch.Stop();
Console.WriteLine("Parallel run" + stopWatch.ElapsedMilliseconds + "ms");
stopWatch.Restart();
Run1();
Run2();
stopWatch.Stop();
Console.WriteLine("Normall run"+stopWatch.ElapsedMilliseconds+"ms");
}
public void ParallelForMethod() {
stopWatch.Start();
for (int i = 0; i < 10000; i++) {
for (int j = 0; j < 60000; j++) {
int sum = 0;
sum += i;
}
}
stopWatch.Stop();
Console.WriteLine("Normalfor run" + stopWatch.ElapsedMilliseconds + "ms");
stopWatch.Reset();
stopWatch.Start();
Parallel.For(0, 10000, item =>
{
for (int j = 0; j < 60000; j++)
{
int sum = 0;
sum += item;
}
});
stopWatch.Stop();
Console.WriteLine("ParallelFor run" + stopWatch.ElapsedMilliseconds + "ms");
}
public void ParallelForMethod2() {
var obj = new Object();
long num = 0;
ConcurrentBag<long> bag = new ConcurrentBag<long>();
stopWatch.Start();
for (int i = 0; i < 10000; i++) {
for (int j = 0; j < 60000; j++)
{
num++;
}
}
stopWatch.Stop();
Console.WriteLine("NormalFor run"+stopWatch.ElapsedMilliseconds+"ms");
stopWatch.Reset();
stopWatch.Start();
Parallel.For(0,10000,item=>{
for(int j=0;j<60000;j++){
lock(obj){
num++;
}}});
stopWatch.Stop();
Console.WriteLine("ParallelFor run"+stopWatch.ElapsedMilliseconds+"ms");
Console.ReadKey();
}
public void ParallelBreak()
{
ConcurrentBag<int> bag = new ConcurrentBag<int>();
stopWatch.Start();
Parallel.For(0, 1000, (i, state) =>
{
if (bag.Count == 300)
{
state.Stop();
return;
}
bag.Add(i);
});
stopWatch.Stop();
Console.WriteLine("Bag count is {}{}", bag.Count, stopWatch.ElapsedMilliseconds+"ms");
}
//</long></long>
}
//public void ParallelForMethod{
//}
}

2 、使用Parallel来做循环
Parallel.For(0,100,i=>{
Console.writeLine(i+"\t");
}); #######从零到99,运行或输出的顺序不对,但是使用for循环的,并行执行的时候会初夏输出顺序不同的问题。
Parallel.Foreach和foreach很类似,
List<int> list=new List<int>();
list.Add(0);
Parallel.ForEach(list,item=>{
DoWork(item);
});
3、异常处理
由于执行的任务是并发的执行的,产生的异常回是多个,简单的Exception不能获取异常,使用AggregateException课可以捕获到一组异常
Task pt = new Task(() =>
{
Task.Factory
.StartNew(() =>
{
throw new Exception("ex 1");
}, TaskCreationOptions.AttachedToParent); Task.Factory
.StartNew(() =>
{
Task.Factory
.StartNew(() =>
{
throw new Exception("ex 2-1");
}, TaskCreationOptions.AttachedToParent); throw new Exception("ex 2");
}, TaskCreationOptions.AttachedToParent); throw new Exception("ex 3");
});
pt.Start()开始任务,异常不会抛出,但必须被处理,以下是若干种方法。
//方法1:
pt.ContinueWith(t =>
{
t.Exception.Handle(ex =>
{
Console.WriteLine(ex.Message);
return true;
});
}, TaskContinuationOptions.OnlyOnFaulted);
//方法2:
pt.ContinueWith(t =>
{
t.Exception.Handle(ex =>
{
Console.WriteLine(ex.GetBaseException().Message);
return true;
});
}, TaskContinuationOptions.OnlyOnFaulted);
//方法3:
pt.ContinueWith(t =>
{
foreach (var ex in t.Exception.Flatten().InnerExceptions)
{
Console.WriteLine(ex.Message);
}
}, TaskContinuationOptions.OnlyOnFaulted);
//方法4:
pt.ContinueWith(t =>
{
foreach (var ex in t.Exception.InnerExceptions)
{
Console.WriteLine(ex.Message);
}
}, TaskContinuationOptions.OnlyOnFaulted);
5、线程并行安全,如下执行的时候输出错误,这是因为List是非线程安全集合,所有的线程都可以修改他的值,造成线程的安全问题。
---------- namespace ConsoleApplication58
{
class Program
{
static void Main(string[] args)
{
PEnumberable Test = new PEnumberable();
Test.ListWithpallel();
Console.ReadKey();
}
}
public class PEnumberable {
public void ListWithpallel() {
List<int> list = new List<int>();
Parallel.For(0, 1000, item =>
{
list.Add(item);
});
Console.WriteLine("list count is{0}",list.Count());
} }}

################
使用system.Collection.Concurrent, 实例ConcurrentBag泛型集合
public void ConcurrentBagwithPallel() {
ConcurrentBag<int> list = new ConcurrentBag<int>();
Parallel.For(0, 10000, item =>
{
list.Add(item);
});
Console.WriteLine("ConcurrentBag's count is{0}", list.Count());
}

现在我们看看 ConcurrentBag中的数据是怎么排列的
public void ConcurrentBagwithPallel() {
ConcurrentBag<int> list = new ConcurrentBag<int>();
Parallel.For(0, 10000, item =>
{
list.Add(item);
});
Console.WriteLine("ConcurrentBag's count is{0}", list.Count());
int n = 0;
foreach (int i in list) {
if (n > 10)
break;
n++; Console.WriteLine("Item{0}={1}", n, i);
}
Console.WriteLine("ConcurrentBag's max item is{0]", list.Max());
}

从上面的执行可窥看出ConcurentBag中的数据排序是乱序的,但是属性Max ,Frist ,Last等都可以使用,关于线程安全的问题还用 Dictionary 的ConcurrentDictionary还用 ConcurrentStack,ConcurrentQueue等
6、Parallel Linq 的用法
C# Parallel并发执行相关问题的更多相关文章
- CUDA编程接口:异步并发执行的概念和API
1.主机和设备间异步执行 为了易于使用主机和设备间的异步执行,一些函数是异步的:在设备完全完成任务前,控制已经返回给主机线程了.它们是: 内核发射; 设备间数据拷贝函数; 主机和设备内拷贝小于64KB ...
- SSIS Design3:并发执行
1,利用优先约束来并发处理数据,Data Flow Task 和 Data Flow Task 1 是并发执行的,而 Data Flow Task2 必须等到 Data Flow Task 和 Dat ...
- C#线程 在某一时间内,只有N个线程在并发执行,其余都在队列中的实现(转载)
具体的需求是 在某一时间点,只有N个线程在并发执行,如果有多余的线程,则排队等候~ 还真是费尽心思啊~最终还是被我攻克了~ 下面我就来说说具体的实现 C#提供了Mutex与Interlocked这两个 ...
- 使用pabot并发执行robotframework的testSuite
下载robotremoteserver-1.0.1.tar.gz.robotframework-pabot-0.22.tar.gz 执行以下命令,以安装pabot: pip install robot ...
- 多线程并发执行任务,取结果归集。终极总结:Future、FutureTask、CompletionService、CompletableFuture
目录 1.Futrue 2.FutureTask 3.CompletionService 4.CompletableFuture 5.总结 ================正文分割线========= ...
- linux shell并发执行命令
一般我们在linux上十一shell命令的批量执行操作,一般使用for或者while 循环进行操作,但是这样有一个问题,for或者while本质上是串行的,并不能,如果某一个命令执行耗费的时间比较长, ...
- Spring-statemachine Action不能并发执行的问题
Spring-statemachine版本:当前最新的1.2.3.RELEASE版本 这几天一直被Action是串行执行搞得很郁闷,写了一个demo专门用来测试: public static void ...
- concurrency parallel 并发 并行 parallelism
在传统的多道程序环境下,要使作业运行,必须为它创建一个或几个进程,并为之分配必要的资源.当进程运行结束时,立即撤销该进程,以便能及时回收该进程所占用的各类资源.进程控制的主要功能是为作业创建进程,撤销 ...
- (五)TestNG测试的并发执行详解
原文链接:https://blog.csdn.net/taiyangdao/article/details/52159065 TestNG在执行测试时,默认suitethreadpoolsize=1, ...
随机推荐
- 堆(heap)与栈(stack)
编程语言书籍中经常解释: 值类型被创建在栈上,引用类型被创建在堆上. 构造函数,原型之类的算是引用类型吗? 5种基本数据类型有Undefined.Null.Boolean.Number 和 Str ...
- mkyaffs2image 生成不了120M的镜像文件的解决方法
下载链接: http://download.csdn.net/download/macrocrazier/3807761 用上述下载的链接会出现Failed to execute /linuxrc ...
- ionic 照相机 Camera
1.官网: https://ionicframework.com/docs/native/camera/#DestinationType 2.引入插件 $ ionic cordova plugin a ...
- Service Mesh
概念 A service mesh is a dedicated infrastructure layer for handling service-to-service communication. ...
- Maven 分模块,启动父工程时异常
1.1 运行方式 Maven方式:命令的 方式1:运行父工程.父工程将各个子模块聚合到一起.将ssh-web打war包发布到tomcat 方式2:直接运行web工程 其他方式:传统的, 部署到to ...
- linux中如何使用终端裁剪图片?
1,首先要安装支持图片裁剪的包: sudo apt-get install imagemagick 需要的话可以update一下, 2,在图片所在位置打开终端,我的我的截图叫screenshot.pn ...
- C++拷贝构造函数(深拷贝&浅拷贝)
对于普通类型的对象来说,它们之间的复制是很简单的,例如: int a=88; int b=a; 而类对象与普通对象不同,类对象内部结构一般较为复杂,存在各种成员变量.下面看一个类对象拷贝的简单例子. ...
- SpringBoot的Session并发控制
⒈是什么? 即控制业务系统中一个用户只能有一个Session ⒉解决方案 1.当这个用户在其它地方登录的时候,把之前的Session失效掉. package cn.coreqi.security.co ...
- 【转】python 历险记(四)— python 中常用的 json 操作
[转]python 历险记(四)— python 中常用的 json 操作 目录 引言 基础知识 什么是 JSON? JSON 的语法 JSON 对象有哪些特点? JSON 数组有哪些特点? 什么是编 ...
- 【转】Python之面向对象与类
[转]Python之面向对象与类 本节内容 面向对象的概念 类的封装 类的继承 类的多态 静态方法.类方法 和 属性方法 类的特殊成员方法 继承层级关系中子类的实例对象对属性的查找顺序问题 一.面向对 ...