博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多线程入门
阅读量:4957 次
发布时间:2019-06-12

本文共 5354 字,大约阅读时间需要 17 分钟。

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
bagStop = new ConcurrentBag
(); Parallel.For(0, 1000, (i, state) => { if (bagStop.Count == 300) { state.Stop(); return; } bagStop.Add(i); }); ConcurrentBag
bagBreak = new ConcurrentBag
(); 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
customs = new List
(); 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
(c => c.Age > 26).ToList(); sw.Stop(); Console.WriteLine("Linq time is {0}.", sw.ElapsedMilliseconds); sw.Restart(); sw.Start(); var result2 = customs.AsParallel().Where
(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
(() => { 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
(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(); } }}

  

转载于:https://www.cnblogs.com/liuqiyun/p/10078161.html

你可能感兴趣的文章
【设计模式】工厂模式
查看>>
两个表格中数据不用是一一对应关系--来筛选不同数据,或者相同数据
查看>>
客户数据库出现大量cache buffer chains latch
查看>>
機械の総合病院 [MISSION LEVEL: C]
查看>>
实战练习细节(分行/拼接字符串/字符串转int/weak和copy)
查看>>
Strict Standards: Only variables should be passed by reference
查看>>
hiho_offer收割18_题解报告_差第四题
查看>>
AngularJs表单验证
查看>>
静态方法是否属于线程安全
查看>>
02号团队-团队任务3:每日立会(2018-12-05)
查看>>
SQLite移植手记1
查看>>
C# windows程序应用与JavaScript 程序交互实现例子
查看>>
HashMap详解
查看>>
js05-DOM对象二
查看>>
mariadb BINLOG_FORMAT = STATEMENT 异常
查看>>
C3P0 WARN: Establishing SSL connection without server's identity verification is not recommended
查看>>
iPhone在日本最牛,在中国输得最慘
查看>>
动态方法决议 和 消息转发
查看>>
WPF自定义搜索框代码分享
查看>>
js 基础拓展
查看>>