using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ReadOnly
{
class Program
{
#region ParallelException
//运行结果:
// Run1
// Run2
// Exception inRun1
// Exception in Run2
public static void Run1()
{
Thread.Sleep(2000);
Console.WriteLine("Run1");
throw new Exception("Exception inRun1");
}
public static void Run2()
{
Thread.Sleep(3000);
Console.WriteLine("Run2");
throw new Exception("Exception in Run2");
}
public static void ParallelInvokeMethod()
{
try
{
Parallel.Invoke(Run1, Run2);
}
catch (AggregateException aex)
{
foreach (var ex in aex.InnerExceptions)
{
Console.WriteLine(ex.Message);
}
}
}
#endregion
#region ParallelBreakStop
//Break: 当然这个是通知并行计算尽快的退出循环,比如并行计算正在迭代100,那么break后程序还会迭代所有小于100的。
//Stop:这个就不一样了,比如正在迭代100突然遇到stop,那它啥也不管了,直接退出。
//运行结果:
//bagStop count is 300
//bagBreak count is 327 694 303
public static void ParallelBreakStop()
{
ConcurrentBag<int> bagStop = new ConcurrentBag<int>();
Parallel.For(0, 1000, (i, state) =>
{
if (bagStop.Count == 300)
{
state.Stop();
return;
}
bagStop.Add(i);
});
ConcurrentBag<int> bagBreak = new ConcurrentBag<int>();
Parallel.For(0, 1000, (i, state) =>
{
if (bagBreak.Count == 300)
{
state.Break();
return;
}
bagBreak.Add(i);
});
Console.WriteLine("bagStop count is " + bagStop.Count);
Console.WriteLine("bagBreak count is " + bagBreak.Count);
}
#endregion
#region 线程安全集合
//Dictionary ConcurrentDictionary,Stack ConcurrentStack,Queue ConcurrentQueue,List ConcurrentBag
//运行结果:
//Linq time is 631
//PLinq time is 537
public static void ParallelLinq()
{
Stopwatch sw = new Stopwatch();
List<Custom> customs = new List<Custom>();
for (int i = 0; i < 2000000; i++)
{
customs.Add(new Custom() { Name = "张三", Age = 21, Address = "北京" });
customs.Add(new Custom() { Name = "李四", Age = 26, Address = "南京" });
customs.Add(new Custom() { Name = "王五", Age = 29, Address = "太原" });
customs.Add(new Custom() { Name = "赵六", Age = 30, Address = "武汉" });
customs.Add(new Custom() { Name = "田七", Age = 60, Address = "徐州" });
}
sw.Start();
var result = customs.Where<Custom>(c => c.Age > 26).ToList();
sw.Stop();
Console.WriteLine("Linq time is {0}.", sw.ElapsedMilliseconds);
sw.Restart();
sw.Start();
var result2 = customs.AsParallel().Where<Custom>(c => c.Age > 26).ToList();
sw.Stop();
Console.WriteLine("PLinq time is {0}.", sw.ElapsedMilliseconds);
}
private class Custom
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
#endregion
#region Task
private static void CreatTask()
{
var task1 = new Task(() =>
{
Console.WriteLine("new Task");
});
task1.Start();
var task2 = Task.Factory.StartNew(() =>
{
Console.WriteLine("Task.Factory.StartNew");
});
}
//task1.Start(); task1.Wait() Task.WaitAll(Task[]) Task.WaitAny(task1,task2) Task.ContinueWith
//Task.WaitAll(tasks,5000);
//for (int i = 0; i<tasks.Length;i++ )
//{
// if (tasks[i].Status != TaskStatus.RanToCompletion)
// {
// Console.WriteLine("Task {0} Error!",i + 1);
// }
//}
//结果:
//task1 Begin
//task2 Begin
//task1 Finish
//Task1的结果:task1 finished
//task1 finished!
//continueTask result!
//task2 Finish
private static void TaskContinueWidth()
{
var task1 = new Task<string>(() =>
{
Console.WriteLine("task1 Begin");
System.Threading.Thread.Sleep(2000);
Console.WriteLine("task1 Finish");
return "task1 finished";
});
var task2 = new Task(() =>
{
Console.WriteLine("task2 Begin");
System.Threading.Thread.Sleep(3000);
Console.WriteLine("task2 Finish");
});
task1.Start();
task2.Start();
var result = task1.ContinueWith<string>(Task1 =>
{
Console.WriteLine("Task1的结果:" + Task1.Result);
Console.WriteLine("task1 finished!");
return "continueTask result!";
});
Console.WriteLine(result.Result.ToString());
}
//Task取消
//运行结果:
//Press enter to cancel task...
//Task取消
//Task 取消成功!
private static void CancelTask()
{
//public class CancellationTokenSource
// 摘要:
// Signals to a System.Threading.CancellationToken that it should be canceled.
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
var task = Task.Factory.StartNew(() =>
{
for (var i = 0; i < 1000; i++)
{
System.Threading.Thread.Sleep(1000);
if (token.IsCancellationRequested)
{
Console.WriteLine("Task 取消成功!");
return;
}
}
}, token);
token.Register(() =>
{
Console.WriteLine("Task取消");
});
Console.WriteLine("Press enter to cancel task...");
Console.ReadKey();
tokenSource.Cancel();
Console.ReadKey();
}
#endregion
static void Main(string[] args)
{
ParallelInvokeMethod();
ParallelBreakStop();
ParallelLinq();
TaskContinueWidth();
CancelTask();
Console.ReadKey();
}
}
}