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. 【译】第三篇 SQL Server安全主体和安全对象

    本篇文章是SQL Server安全系列的第三篇,详细内容请参考原文. 一般来说,你通过给主体分配对象的权限来实现SQL Server上的用户与对象的安全.在这一系列,你会学习在SQL Server实例 ...

  2. nodejs设置允许跨域

    //设置服务器跨域权限app.use(function (req, res, next) {    res.header("Access-Control-Allow-Origin" ...

  3. 【NLP CS224N笔记】Lecture 2 - Word Vector Representations: word2vec

    I. Word meaning Meaning的定义有很多种,其中有: the idea that is represented by a word,phrase,etc. the idea that ...

  4. WindowsPE权威指南-PE文件头中的重定位表

    PE加载的过程 任何一个EXE程序会被分配4GB的内存空间,用户层处理低2G的内存,驱动处理高2G的内存. 1.双击EXE程序,操作系统开辟一个4GB的空间. 2.从ImageBase决定了加载后的基 ...

  5. 如何在Delphi 中使用 DevExpressVCL的 CxGrid与CxTreeList,编辑某列后计算另一列的值

    如何在Delphi 中使用 DevExpressVCL的 CxGrid与CxTreeList,编辑某列后计算另一列的值:比如 输入 单价,数量,计算金额. 参考: 1.  输入 单价,数量,计算金额 ...

  6. 两种 AuthorizationSchemes 在 ASP.NET Core 2

    Welcome to IdentityServer4:  https://identityserver4.readthedocs.io/en/release/   支持 ASP.NET Core 2 ...

  7. aiohttp的笔记之TCPConnector

    TCPConnector维持链接池,限制并行连接的总量,当池满了,有请求退出再加入新请求.默认是100,limit=0的时候是无限制 1.use_dns_cache: 使用内部DNS映射缓存用以查询D ...

  8. python3+requests库框架设计01-自动化测试框架需要什么?

    什么是自动化测试框架 关于自动化测试框架的定义有很多,在我大致理解下就是把能实现不同功能的软件组合在一起,实现特定的目的,这就是一个简单的自动化测试框架. 接口自动化测试框架核心无非是选择 一个用来编 ...

  9. hibernate框架学习之数据抓取(加载)策略helloworld

    package cn.itcast.h3.query.hql; import java.util.List; import org.hibernate.Query; import org.hibern ...

  10. hibernate框架学习之数据查询(QBC)helloworld

    package cn.itcast.h3.query.hql; import java.util.List; import org.hibernate.Criteria; import org.hib ...