1

C# 创建连接块管道,为甚麽运行出错

这里是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using System.IO;

namespace shujuliu
{
class Program
{
static void Main(string[] args)
{
var target = SetupPipeline();
target.Post(@"E:\临时文件\C#\assssss");//文件夹
Console.Read();

    }

    static IEnumerable<string> GetFileNames(string path)
    {
        foreach (var fileName in Directory.EnumerateFiles(path, "*.cs"))
        {
            //Console.WriteLine(fileName);
            yield return fileName;
        }
    }
    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)
                {
                    yield return line; //这里出错,
                }
            }
        }

    }
    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;
                }
            }
        }
    }
    static ITargetBlock<string> SetupPipeline()
    {
        var fileNamesForPath = new TransformBlock<string, IEnumerable<string>>(path => { return GetFileNames(path); });
        var lines = new TransformBlock<IEnumerable<string>, IEnumerable<string>>(files => { return LoadLines(files); });
        var words = new TransformBlock<IEnumerable<string>, IEnumerable<string>>(lines0 => { return LoadLines(lines0); });
        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;
    }

}

}
这是控制台应用程序,编译没问题,
但是运行到 LoadLines(IEnumerable filenames)后,输出的 yield return line; 这个line会替换filename导致找不到文件。

查看全部
wzt2017l
wzt2017l
2017/10/25 08:38
  • 数据块
  • c#
  • 管道
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复