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. PLSql的使用

    1.安装 plsqldeveloper和数据库驱动-ODAC 2.在数据库驱动ODAC中添加 Oracle客户端的网络服务名配置文件tnsnames.ora 路径为: 3.汉化 直接运行Languag ...

  2. You Only Look Once: Unified, Real-Time Object Detection(翻译)

    0 - 摘要 我们提出了YOLO,一种新的物体检测方法.之前的物体检测工作是通过重新使用分类器来进行检测.相反,我们将对象检测抽象为一个回归问题,描述为以空间分隔的边界框和相关的类别概率.一个简单的神 ...

  3. vue 学习笔记—Es6

    // 第一部分 /* console.log(a+'c'); var a = 1; console.log(b+'c'); let b =1; */ // 上述代码 left定义报错 原因: /* v ...

  4. 嵌入式开发平台迅为iTOP-4412开发板-ssh常见问题以及解决方法

    一.基本网络,软件安装以及配置 ssh 软件无法登陆 Ubuntu,有可能是网络不通.SSH 软件未安装.环境变量没配置.防 火墙未关闭等. 1. 网络连接 使用 ssh 传输文件的前提是网络顺畅,即 ...

  5. ASP.NET MVC - WEB API

    ASP.NET WEB API 与WEB API有关的类型 HttpMessageHandler(System.Net.Http)(消息处理器) 表示Http请求的处理程序,处理程序类似于Http管道 ...

  6. 20165234 《Java程序设计》实验一 Java开发环境的熟悉

    一.实验报告封面 课程:Java程序设计  班级:1652班  姓名:刘津甫  学号:20165234 指导教师:娄嘉鹏  实验日期:2018年4月2日 实验时间:15:35 - 17:15  实验序 ...

  7. 拿什么守护你的Node.JS进程: Node出错崩溃了怎么办?

    被吐嘈的NodeJS的异常处理 许多人都有这样一种映像,NodeJS比较快: 但是因为其是单线程,所以它不稳定,有点不安全,不适合处理复杂业务: 它比较适合对并发要求比较高,而且简单的业务场景. 在E ...

  8. SQL NOLOCK大杂烩

    今天碰到NOLOCK 的问题,就查阅了一些资料,做了相关了解:总结了比较经典,朴实的两篇在此. 电梯直达: SQL Server 中WITH (NOLOCK)浅析 文章本想大篇幅摘抄,因为担心链接失效 ...

  9. C# string.join

    String.Join 方法 平常工作中经常用到string.join()方法,在vs 2017用的运行时(System.Runtime, Version=4.2.0.0)中,共有九个(重载)方法. ...

  10. 【转】Linux下gcc生成和使用静态库和动态库详解

    一.基本概念 1.1 什么是库 在Windows平台和Linux平台下都大量存在着库. 本质上来说,库是一种可执行代码的二进制形式,可以被操作系统载入内存执行. 由于windows和linux的平台不 ...