一个简单 System.Threading.Tasks.Dataflow.TransformBlock 示例
2019-07-30 16:37 音乐让我说 阅读(545) 评论(0) 编辑 收藏 举报直接贴代码了:
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks.Dataflow; namespace DataFlowSample { class Program { static void Main() { var target = SetupPipeline(); target.Post(@"D:\Source\BenchmarkAndSpanExample-master\BenchmarkAndSpanExample"); Console.ReadLine(); } public static IEnumerable<string> GetFileNames(string path) { foreach (var fileName in Directory.EnumerateFiles(path, "*.cs")) { yield return fileName; } } public static IEnumerable<string> LoadLines(IEnumerable<string> fileNames) { foreach (var fileName in fileNames) { using (FileStream stream = File.OpenRead(fileName)) { var reader = new StreamReader(stream); string line = null; while ((line = reader.ReadLine()) != null) { //WriteLine($"LoadLines {line}"); yield return line; } } } } public static IEnumerable<string> GetWords(IEnumerable<string> lines) { foreach (var line in lines) { string[] words = line.Split(' ', ';', '(', ')', '{', '}', '.', ','); foreach (var word in words) { if (!string.IsNullOrEmpty(word)) yield return word; } } } public static ITargetBlock<string> SetupPipeline() { var fileNamesForPath = new TransformBlock<string, IEnumerable<string>>( path => GetFileNames(path)); var lines = new TransformBlock<IEnumerable<string>, IEnumerable<string>>( fileNames => LoadLines(fileNames)); var words = new TransformBlock<IEnumerable<string>, IEnumerable<string>>( lines2 => GetWords(lines2)); var display = new ActionBlock<IEnumerable<string>>( coll => { foreach (var s in coll) { Console.WriteLine(s); } }); fileNamesForPath.LinkTo(lines); lines.LinkTo(words); words.LinkTo(display); return fileNamesForPath; } } }
谢谢浏览!
作者:音乐让我说(音乐让我说 - 博客园)
出处:http://music.cnblogs.com/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步