C# 任务、线程、同步(五)
1、数据流使用 TPL Data Flow 类库
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 // ActionBlock(); 6 // SourceAndTargetBlocksSample(); 7 var target = SetupPipeline(); 8 target.Post("../../"); 9 Console.ReadLine(); 10 11 } 12 #region ActionBlock 13 static void ActionBlock() 14 { 15 var processInput = new ActionBlock<string>(s => { Console.WriteLine("user input : {0}", s); }); 16 17 bool exit = false; 18 19 while (!exit) 20 { 21 string input = Console.ReadLine(); 22 if (string.Compare(input, "exit", ignoreCase: true) == 0) 23 { 24 exit = true; 25 } 26 else 27 processInput.Post(input); 28 } 29 } 30 #endregion 31 32 #region BufferBlock 33 static void SourceAndTargetBlocksSample() 34 { 35 Task t1 = Task.Run(() => Producer()); 36 Task t2 = Task.Run(() => Consumer()); 37 38 Task.WaitAll(t1, t2); 39 } 40 static BufferBlock<string> buffer = new BufferBlock<string>(); 41 static void Producer() 42 { 43 bool exit = false; 44 while (!exit) 45 { 46 string input = Console.ReadLine(); 47 if (string.Compare(input, "exit", ignoreCase: true) == 0) 48 { 49 exit = true; 50 } 51 else 52 buffer.Post(input); 53 } 54 } 55 static async void Consumer() 56 { 57 while(true) 58 { 59 string data = await buffer.ReceiveAsync(); 60 Console.WriteLine("user input : {0} ", data); 61 } 62 } 63 64 #endregion 65 66 #region 管道使用 67 static ITargetBlock<string> SetupPipeline() 68 { 69 var fileNamesForPath = new TransformBlock<string, IEnumerable<string>>(path => { return GetFileNames(path); }); 70 var lines = new TransformBlock<IEnumerable<string>, IEnumerable<string>>(fileNames => { return LoadLines(fileNames); }); 71 var words = new TransformBlock<IEnumerable<string>, IEnumerable<string>>(lines2 => { return GetWords(lines2); }); 72 73 var display = new ActionBlock<IEnumerable<string>>(coll => 74 { 75 foreach (var item in coll) 76 { 77 Console.WriteLine(item); 78 } 79 }); 80 81 fileNamesForPath.LinkTo(lines); 82 lines.LinkTo(words); 83 words.LinkTo(display); 84 return fileNamesForPath; 85 } 86 static IEnumerable<string> GetFileNames(string path) 87 { 88 foreach (var item in Directory.EnumerateFiles(path,"*.cs")) 89 { 90 yield return item; 91 } 92 } 93 94 static IEnumerable<string> LoadLines(IEnumerable<string> fileName) 95 { 96 foreach (var item in fileName) 97 { 98 using(FileStream stream=File.OpenRead(item)) 99 { 100 var reader = new StreamReader(stream); 101 string line = null; 102 while((line=reader.ReadLine())!=null) 103 { 104 yield return line; 105 } 106 } 107 } 108 } 109 static IEnumerable<string> GetWords(IEnumerable<string> lines) 110 { 111 foreach (var item in lines) 112 { 113 string[] words = item.Split(' ', ';', '(', ')', '{', '}', '.', ','); 114 foreach(var word in words) 115 { 116 if (!string.IsNullOrEmpty(word)) 117 yield return word; 118 } 119 } 120 } 121 122 #endregion 123 }
鹰击长空,鱼翔浅底