2011-09-23 53 views
5

我已经将一个简单的应用程序放在一起,该应用程序监视文件创建事件,从文件内容创建一些对象并进行一些处理。下面是示例代码:使PLINQ和BlockingCollection一起工作

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?

回答

2

这就是.WithMergeOptions(ParallelMergeOptions.NotBuffered)应该设计的。

+0

这工作得很好。非常感谢! – yuramag