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并发执行相关问题的更多相关文章

  1. CUDA编程接口:异步并发执行的概念和API

    1.主机和设备间异步执行 为了易于使用主机和设备间的异步执行,一些函数是异步的:在设备完全完成任务前,控制已经返回给主机线程了.它们是: 内核发射; 设备间数据拷贝函数; 主机和设备内拷贝小于64KB ...

  2. SSIS Design3:并发执行

    1,利用优先约束来并发处理数据,Data Flow Task 和 Data Flow Task 1 是并发执行的,而 Data Flow Task2 必须等到 Data Flow Task 和 Dat ...

  3. C#线程 在某一时间内,只有N个线程在并发执行,其余都在队列中的实现(转载)

    具体的需求是 在某一时间点,只有N个线程在并发执行,如果有多余的线程,则排队等候~ 还真是费尽心思啊~最终还是被我攻克了~ 下面我就来说说具体的实现 C#提供了Mutex与Interlocked这两个 ...

  4. 使用pabot并发执行robotframework的testSuite

    下载robotremoteserver-1.0.1.tar.gz.robotframework-pabot-0.22.tar.gz 执行以下命令,以安装pabot: pip install robot ...

  5. 多线程并发执行任务,取结果归集。终极总结:Future、FutureTask、CompletionService、CompletableFuture

    目录 1.Futrue 2.FutureTask 3.CompletionService 4.CompletableFuture 5.总结 ================正文分割线========= ...

  6. linux shell并发执行命令

    一般我们在linux上十一shell命令的批量执行操作,一般使用for或者while 循环进行操作,但是这样有一个问题,for或者while本质上是串行的,并不能,如果某一个命令执行耗费的时间比较长, ...

  7. Spring-statemachine Action不能并发执行的问题

    Spring-statemachine版本:当前最新的1.2.3.RELEASE版本 这几天一直被Action是串行执行搞得很郁闷,写了一个demo专门用来测试: public static void ...

  8. concurrency parallel 并发 并行 parallelism

    在传统的多道程序环境下,要使作业运行,必须为它创建一个或几个进程,并为之分配必要的资源.当进程运行结束时,立即撤销该进程,以便能及时回收该进程所占用的各类资源.进程控制的主要功能是为作业创建进程,撤销 ...

  9. (五)TestNG测试的并发执行详解

    原文链接:https://blog.csdn.net/taiyangdao/article/details/52159065 TestNG在执行测试时,默认suitethreadpoolsize=1, ...

随机推荐

  1. IIS7配置Gzip压缩

    II7中自带了gzip功能,理论上应该比ii6配置起来应该简单一点,但是容易出的问题比较多.有的II7配置web服务器角色的时候可能没有安装启用动态内容压缩,所以这个钩子是灰色的,需要再次安装. 如图 ...

  2. python(十一)面向切面编程AOP和装饰器

    二.装饰器 装饰器可以在给函数修改功能的同时并不改变这个函数本身.(以下用的都是python2.7) 首先,在python里面函数是对象,在下面的函数里"fun"是函数也是对象可以 ...

  3. oracle dblink的创建与使用

    一.什么是DBLINK dblink,顾名思义就是数据库的链接. 当我们要跨本地数据库访问另一个数据库中的表的数据时,在本地数据库中就必须要创建远程数据库的dblink,通过该dblink就可以达到访 ...

  4. struts文件下载机制

    Struts2 中使用 type="stream" 的 result 进行下载即可.只用提供一个输入流inputStream,剩下的输出工作struts帮我们做. 例子一: 1.可 ...

  5. centos6.5环境安装zookeeper-3.4.5

    1.将zookeeper-3.4.5.tar.gz压缩包拷贝到/usr/local/src, 并用如下命令解压 tar -xzf  zookeeper-3.4.5.tar.gz 2.在zookeepe ...

  6. YOLOv1

    学习资料: https://blog.paperspace.com/tag/series-yolo/ https://blog.csdn.net/u014380165/article/details/ ...

  7. Ubuntu 16.04 Matlab2015b安装

    小白一个,安装过程参考了一大堆教程. 这里记录一下. 一.安装 1) sudo mkdir /media/matlab 2) cd 到下载的镜像文件所在文件夹 3) 挂载镜像: sudo mount ...

  8. AD7729_双通道Sigma-Delta ADC

    sigma-delta adc的原理,就是通过一种结构把量化噪声调制到频谱的高端,也即对量化噪声而言,sdm是一个高通滤波器,而对基带信号则等价为一个全通滤波器,这样等价的基带信号的量化噪声就很小了, ...

  9. vc++基础班[28]---动态数组及动态链表的讲解

    C++中也有相应的动态数组.动态链表.映射表的模板类,就是STL中的:vector.list.map 他们属于C++标准中的一部分,对于程序的移植性来说也是不错的,但是在MFC编程中使用 CArray ...

  10. android studio 学习之一 安装和基本使用

    一.简介 Android Studio 是一个Android集成开发工具,基于IntelliJ IDEA. 类似 Eclipse ADT,Android Studio 提供了集成的 Android 开 ...