有没有办法释放内存并防止以下代码在MS-Word中崩溃? 我收到以下错误消息:
此方法或属性不可用,因为存在内存或磁盘问题。
Sub vbaTest()
Dim doc As Document
Dim sty As Style
Dim s As Style
Dim readingOrder As WdReadingOrder
Dim i As Integer
Set doc = ActiveDocument
Set sty = doc.Styles(wdStyleNormal)
For i = 0 To 100
readingOrder = sty.ParagraphFormat.readingOrder
For Each s In doc.Styles
s.Font.SizeBi = s.Font.Size + 3
Next
Set s = Nothing
Next
Set sty = Nothing
End Sub
- 或 -
public void CsharpRibbon_Click(O.IRibbonControl c)
{
var doc = app.ActiveDocument;
var style = doc.Styles[Wd.WdBuiltinStyle.wdStyleNormal];
for (int i = 0; i < 100; i++)
{
var readingOrder = style.ParagraphFormat.ReadingOrder;
foreach (Wd.Style s in doc.Styles)
s.Font.SizeBi = s.Font.Size + 3;
}
}
上面的代码实际上没有任何帮助。我有一个功能区按钮,我注意到重复按下按钮会导致崩溃(在Word会话中大约5或6次)。我删除了代码并添加了for循环来模拟多次按下按钮。
答案 0 :(得分:1)
我不确定这是否是您的错误,因为100次迭代似乎不足以导致内存错误,但VSTO使用COM对象,必须在使用后释放。这样做的简单方法是:
Paragraph para = Paragraphs[1];
// etc.
Marshal.ReleaseComObject(yourObject);
还有VSTO Contrib使这更容易一些。而不是打电话给ReleaseComObject
,你会做这样的事情:
using (var doc = Document.WithComCleanup())
using (var paragraphs = doc.Resource.Paragraphs.WithComCleanup())
{
int count = paragraphs.Resource.Count;
// etc.
}
或者,对于集合:
foreach (Paragraph para in Paragraphs.ComLinq<Paragraph>())
{
int pageBreakBefore = para.PageBreakBefore;
// etc.
}