1

Parallel.Foreachまたは何かを使用してこのコードを最適化することは可能ですか?

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 と SharpZipLibZipOutputStreamが位置の変更またはシークをサポートしていないことです。

複数のスレッドから zip ストリームに書き込むと、エラーが発生します。また、結果ストリームを ConcurrentStack に蓄積することもできません。これは、アプリケーションが 1000 以上のドキュメントを処理でき、その場でストリームを圧縮してクラウドに保存する必要があるためです。

これを解決する方法はありますか?

4

2 に答える 2

1

ProducerConsumerQueueof (Producer-Consumer パターン)を使用して解決しました。

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);
    }
}
于 2013-07-09T13:43:31.880 に答える
0

次のように、並列 foreach 内で zipstream を宣言してみてください。

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();
                }
            });

さよなら!

于 2013-07-08T09:30:57.617 に答える