2013-07-08 45 views
0

是否有可能使用Parallel.Foreach或其他来优化此代码?并行压缩C#

using (var zipStream = new ZipOutputStream(OpenWriteArchive())) 
{ 
    zipStream.CompressionLevel = CompressionLevel.Level9;  
    foreach (var document in docuemnts) 
    { 
     zipStream.PutNextEntry(GetZipEntryName(type));  
     using (var targetStream = new MemoryStream()) // document stream 
     { 
      DocumentHelper.SaveDocument(document.Value, targetStream, type);  
      targetStream.Position = 0; targetStream.CopyTo(zipStream); 
     }  
     GC.Collect(); 
    }; 
} 

问题是DotNetZip的和SharpZipLib的ZipOutputStream不支持位置改变或寻求。

从多个线程写入zip流会导致错误。将结果流积累到 也是不可能的ConcurrentStack beacuse应用程序可以与1000多个文档一起使用,并且应该在运行时将流压缩并保存到云 中。

有什么办法解决这个问题吗?

+0

你*有*将所有文件压缩到一个相同的档案? –

+0

是的,所有条目(文档)应该放在同一个存档中 –

+0

如果ZipOutputStream * did *支持查找和位置更改,并且您设法实现了一个允许多个线程同时写入的编组系统,它仍然会成为你的瓶颈。 这样的编组系统可能会导致比平行处理更多的开销。 –

回答

0

通过使用ProducerConsumerQueue(生产者 - 消费者模式)来解决。

using (var queue = new ProducerConsumerQueue<byte[]>(HandlerDelegate)) 
{ 
    Parallel.ForEach(documents, document => 
    { 
     using (var documentStream = new MemoryStream()) 
     { 
      // saving document here ... 

      queue.EnqueueTask(documentStream.ToArray()); 
     } 
    }); 
} 

protected void HandlerDelegate(byte[] content) 
{ 
    ZipOutputStream.PutNextEntry(Guid.NewGuid() + ".pdf"); 

    using (var stream = new MemoryStream(content)) 
    { 
     stream.Position = 0; stream.CopyTo(ZipOutputStream); 
    } 
} 
0

尝试decleare zipstream并行的foreach里面,如:

Parallel.ForEach(docuemnts, (document) => 
      { 
       using (var zipStream = new ZipOutputStream(OpenWriteArchive())) 
       { 
        zipStream.CompressionLevel = CompressionLevel.Level9; 
        zipStream.PutNextEntry(GetZipEntryName(type)); 
        using (var targetStream = new MemoryStream()) // document stream 
        { 
         DocumentHelper.SaveDocument(document.Value, targetStream, type); 
         targetStream.Position = 0; targetStream.CopyTo(zipStream); 
        } 
        GC.Collect(); 
       } 
      }); 

再见!

+0

所有文档应该在同一个档案中 –