内容总结
1.并行集合/线程安全集合
1)方法ListWithParallel()
2)方法ConcurrentBagWithParallel()
2.Parallel Linq的用法及性能
1)AsParallel
2)Groupby 与 ToLookup
3)补充ToLookup
3.Task
1)创建方法
2)任务控制
3)嵌套
4)异常处理
1.并行集合/线程安全集合
参考资料:https://www.cnblogs.com/yunfeifei/p/3998783.html
代码简述
1、创建PEnumerable类,类中包括两个方法:ListWithParallel()、ConcurrentBagWithParallel()
2、ListWithParallel():计算List列表中元素个数
3、ConcurrentBagWithParallel():计算List列表中元素个数,循环查看列表中数据的存储顺序
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp_parallel1
{
class Program
{
static void Main(string[] args)
{
PEnumerable pEnumerable = new PEnumerable();
pEnumerable.ListWithParallel();
pEnumerable.ConcurrentBagWithParallel();
}
}
public class PEnumerable
{
public void ListWithParallel()
{
List<int> list = new List<int>();
Parallel.For(0, 10000, item =>
{
list.Add(item);
});
Console.WriteLine("List's count is {0}", list.Count);
}
public void ConcurrentBagWithParallel()
{
ConcurrentBag<int> list2 = new ConcurrentBag<int>();
Parallel.For(0, 10000, item =>
{
list2.Add(item);
});
Console.WriteLine("ConcurrentBag's count is {0}", list2.Count);
int n = 0;
foreach (var i in list2)
{
if(n>10)
{
break;
}
n++;
Console.WriteLine("Item[{0}] = {1}", n, i);
}
}
}
}
运行结果:
方法ListWithParallel()
1、理论结果:List中的元素个数应为10000
2、原因:所有的线程均可修改非线性安全集合List中的值方法ConcurrentBagWithParallel()
1、实际结果与理论结果同
2、列表集合中的数据并不是按顺序排列的
2.Parallel Linq的用法及性能
参考资料:https://www.cnblogs.com/yunfeifei/p/3998783.html
1)AsParallel
代码简述
1、创建PEnumerable类,类中包括两个方法:TestPLinq1()、TestPLinq2()
2、TestPLinq1()、TestPLinq2():打印是否使用AsParallel时查询数据所在位置的程序运行时间
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp_parallel1
{
class Program
{
static void Main(string[] args)
{
PEnumerable pEnumerable = new PEnumerable();
pEnumerable.TestPLinq1();
pEnumerable.TestPLinq2();
}
}
/// <summary>
/// AsParallel
/// </summary>
public class Custom
{
public string Name {
get; set; }
public int Age {
get; set; }
public string Address {
get; set; }
}
public class PEnumerable
{
/// <summary>
/// AsParallel
/// </summary>
public void TestPLinq1()
{
Stopwatch stopwatch = new Stopwatch();
List<Custom> customs