【发布时间】:2014-03-28 16:54:13
【问题描述】:
根据this article,OpenXML 在“MemoryStreams 达到高水位线”时不是线程安全的,必须切换到独立存储。
这发生在甚至小于 1mb 的工作簿上,因为未压缩的数据可能是该大小的 10 倍。
我确实需要同时创建 xlsx 文件,尤其是并发异常大的文件。 MS 解决方案是实现类似以下的内容(从 C# 转换而来),但我不知道如何处理。
Public Class PackagePartStream
Private _stream As Stream
Private Shared _m As New Mutex(False)
Public Sub New(ByVal Stream As Stream)
_stream = Stream
End Sub
Public Function Read(ByVal buffer() As Byte, ByVal offset As Integer, ByVal count As Integer) As Integer
Return _stream.Read(buffer, offset, count)
End Function
Public Sub Write(ByVal buffer() As Byte, ByVal offset As Integer, ByVal count As Integer)
_m.WaitOne(Timeout.Infinite, False)
_stream.Write(buffer, offset, count)
_m.ReleaseMutex()
End Sub
Public Sub Flush()
_m.WaitOne(Timeout.Infinite, False)
_stream.Flush()
_m.ReleaseMutex()
End Sub
End Class
到目前为止,我最好的猜测是这样的,但我觉得我已经过度简化了,互斥锁需要更接近处理 OpenXML 的 WriteElement 的函数
Dim stream As New PackagePartStream()
Using document As SpreadsheetDocument = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, True)
WriteExcelFile(ds, document)
End Using
我没有在 .NET 中做太多线程,但希望有人能指出我正确的方向。
【问题讨论】:
标签: vb.net multithreading excel openxml-sdk