使PLINQ和BlockingCollection一起工作

时间:2011-09-23 18:04:24

标签: c# delay plinq

我已经整理了一个简单的应用程序,它监视文件创建事件,从文件内容创建一些对象,并进行一些处理。以下是示例代码:

class Program
{
    private const string Folder = "C:\\Temp\\InputData";

    static void Main(string[] args)
    {
        var cts = new CancellationTokenSource();
        foreach (var obj in Input(cts.Token))
            Console.WriteLine(obj);
    }

    public static IEnumerable<object> Input(CancellationToken cancellationToken)
    {
        var fileList = new BlockingCollection<string>();

        var watcher = new FileSystemWatcher(Folder);
        watcher.Created += (source, e) =>
        {
            if (cancellationToken.IsCancellationRequested)
                watcher.EnableRaisingEvents = false;
            else if (Path.GetFileName(e.FullPath) == "STOP")
            {
                watcher.EnableRaisingEvents = false;
                fileList.CompleteAdding();
                File.Delete(e.FullPath);
            }
            else
                fileList.Add(e.FullPath);
        };
        watcher.EnableRaisingEvents = true;

        return from file in
                   fileList.GetConsumingEnumerable(cancellationToken)
               //.AsParallel()
               //.WithCancellation(cancellationToken)
               //.WithDegreeOfParallelism(5)
               let obj = CreateMyObject(file)
               select obj;
    }

    private static object CreateMyObject(string file)
    {
        return file;
    }
}

一切正常,但是当我取消注释AsParallel(以及接下来的两行)时,它不会立即产生结果。这种延迟可能是由PLINQ分区引起的?但是,我希望此查询在将项添加到BlockingCollection后立即生成项。这可以用PLINQ来实现吗?

1 个答案:

答案 0 :(得分:2)

这就是.WithMergeOptions(ParallelMergeOptions.NotBuffered)的设计目标。