简体   繁体   English

如何防止MS-Word内存错误

[英]How to prevent MS-Word memory error

Is there a way of releasing memory and preventing the following code from crashing in MS-Word? 有没有一种释放内存并防止以下代码在MS-Word中崩溃的方法? I get the following error message: 我收到以下错误消息:

This method or property is not available because there is a memory or disk problem. 此方法或属性不可用,因为存在内存或磁盘问题。

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

-- or -- - 要么 -

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

The code above doesn't really do anything helpful. 上面的代码并没有真正的帮助。 I have a ribbon button that I noticed causes a crash on repeated button presses (around 5 or 6 times in a Word session). 我有一个功能区按钮,我注意到重复按下按钮会导致崩溃(在Word会话中大约5或6次)。 I stripped back the code and added the for loop to simulate multiple presses of the button. 我剥离了代码,并添加了for循环来模拟按钮的多次按下。

I'm not sure if this is your error, because 100 iterations doesn't seem like enough to cause memory errors, but VSTO uses COM objects, which must be released after use. 我不确定这是否是您的错误,因为100次迭代似乎不足以引起内存错误,但是VSTO使用COM对象,使用后必须将其释放。 The simple way to do this is: 执行此操作的简单方法是:

Paragraph para = Paragraphs[1];
// etc.
Marshal.ReleaseComObject(yourObject);

There's also VSTO Contrib which makes this a little easier. 还有VSTO Contrib ,这使此操作变得容易一些。 Instead of making a call to ReleaseComObject , you would do something like this: 无需调用ReleaseComObject ,您可以执行以下操作:

using (var doc = Document.WithComCleanup())
using (var paragraphs = doc.Resource.Paragraphs.WithComCleanup())
{
    int count = paragraphs.Resource.Count;
    // etc.
}

Or, for collections: 或者,对于收藏:

foreach (Paragraph para in Paragraphs.ComLinq<Paragraph>())
{
    int pageBreakBefore = para.PageBreakBefore;
    // etc.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM