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, ...
随机推荐
- 3年java工作经验必备技能
3年工作经验的Java程序员应该具备的技能 一.Java基础 1.String类为什么是final的. 2.HashMap的源码,实现原理,底层结构. 3.反射中,Class.forName和clas ...
- java解压缩zip
依赖的包: <!-- https://mvnrepository.com/artifact/org.apache.ant/ant --> <dependency> <gr ...
- 【mmall】url-pattern配置为"/"和"/*"的区别
我的代码 <!-- springmvc --> <servlet> <servlet-name>springmvc</servlet-name> < ...
- bzoj3262: 陌上花开(CDQ+树状数组处理三维偏序问题)
题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=3262 题目大意:中文题目 具体思路:CDQ可以处理的问题,一共有三维空间,对于第一维我们 ...
- ASP.NET MVC 4 从示例代码展开,连接默认SQL Server数据库
VS2013里面,点击菜单[视图]-[SQL server对象资源管理器],右键点击[SQL Server]节点,选择[添加SQL Server]自动生成. 这只是开始,可以让网上下载下来的例子运行出 ...
- CF1101G (Zero XOR Subset)-less
题目地址:CF1101G (Zero XOR Subset)-less 线性基基础题 预处理一个前缀异或和 \(s_i\) 这样题目就变成了:在 \(n\) 个 \(s_i\) 中尽量选择多的数使选择 ...
- Path Sum I && II & III
Path Sum I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that ad ...
- WCF之endpoint的binding属性
最近在回顾之前做的wcf项目时,发现这个binding的属性有BasicHttpBinding,WSHttpBinding,webHttpBinding等几种方式.但是其中的区别当时未深入研究.现在网 ...
- jqueryui组件progressbar进度条和日期组件datepickers的简单使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 【原创】Linux基础之opensuse15
装机 装机之后执行 sudo zypper ar -fc https://mirrors.aliyun.com/opensuse/distribution/leap/15.0/repo/oss ope ...