我在我的申请中发现了一个持续的泄漏。在使用内存分析器进行检查之后,我发现该课程来自Microsoft Speech.Synthesizer的一些对象。
所以我建立了一个玩具项目来验证这个假设:
//Toy示例显示Speech.Synthesizer对象中的内存泄漏
static void Main(string[] args)
{
string text = "hello world. This is a long sentence";
PromptBuilder pb = new PromptBuilder();
pb.StartStyle(new PromptStyle(PromptRate.ExtraFast));
pb.AppendText(text);
pb.EndStyle();
SpeechSynthesizer tts = new SpeechSynthesizer();
while (true)
{
//SpeechSynthesizer tts = new SpeechSynthesizer();
Console.WriteLine("Speaking...");
tts.Speak(pb);
//Print private working set sieze
Console.WriteLine("Memory: {0} KB\n", (Process.GetCurrentProcess().PrivateMemorySize64 / 1024).ToString("0"));
//tts.Dispose(); //also this doesn't work as well
//tts = null;
GC.Collect(); //a little help, but still leaks
}
}结果证实了内存泄漏是来自Speech.Synthesizer。
Speaking...内存: 42184 KB
说到..。内存: 42312 KB
说到..。内存: 42440 KB
说到..。内存: 42568 KB
说到..。内存: 42696 KB
说到..。内存: 42824 KB
说到..。内存: 43016 KB
说到..。内存: 43372 KB
我搜索了一下,发现很多其他人也遇到了同样的问题: 1:SpeechSynthesizer中的常量内存泄漏 2:http://connect.microsoft.com/VisualStudio/feedback/details/664196/system-speech-has-a-memory-leak
但遗憾的是,我没有找到任何解决办法。既然这是很久以前就提出的问题了,所以我想问一问它是否解决了?
非常感谢。
更新:
当我切换到使用SAPI而不是.Net Speech.Synthesizer包时(尽管它们本质上是一样的),内存就停止泄漏了。
为什么这两种调用行为(SAPI与.net语音包)有不同的内存行为?正如后者所显示的那样,它只是对前者的SAPI dll.的包装器。
static void Test2()
{
//SAPI COM component this time
SpeechLib.SpVoiceClass tts = new SpeechLib.SpVoiceClass();
tts.SetRate(5);
string text = "hello world. This is a long sentence";
//tts.Speak("helloWorld", SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault);
while (true)
{
Console.WriteLine("Speaking...");
tts.Speak(text, SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault);
//Print private working set sieze
Console.WriteLine("Memory: {0} KB\n", (Process.GetCurrentProcess().PrivateMemorySize64 / 1024).ToString("0"));
GC.Collect();
}}
内存: 32044 KB
说到..。内存: 32044 KB
说到..。内存: 32044 KB
说到..。内存: 32044 KB
说到..。内存: 32044 KB
说到..。内存: 32044 KB
说到..。内存: 32044 KB
说到..。内存: 32044 KB
发布于 2012-06-26 21:01:12
最后解决办法:
谷歌相关关键词告诉我,它实际上是微软的一个bug。
当我切换到使用SAPI而不是.Net Speech.Synthesizer包时(尽管它们本质上是一样的),内存就停止泄漏了。
发布于 2012-05-22 18:15:23
我不确定SpeechSynthesizer的所有细节,但是您可以在这里尝试使用一次性模式。因为SpeechSynthesizer实现了IDisposable
您的代码如下所示:
while (true)
{
using (SpeechSynthesizer tts = new SpeechSynthesizer())
{
Console.WriteLine("Speaking...");
tts.Speak(pb);
//Print private working set sieze
Console.WriteLine("Memory: {0} KB\n",(Process.GetCurrentProcess().PrivateMemorySize64 / 1024).ToString("0"));
}
}如果您注意到这与微软的示例这里非常相似
这看起来实际上是内存泄漏,您试过使用Microsoft.Speech运行时吗?语法看起来非常相似,他们已经提到它不应该有相同的问题。
发布于 2018-05-08 08:51:42
我知道这是个老生常谈,但这个问题还有另一个解决办法。使用Microsoft.Speech.Synthesis.SpeechSynthesizer而不是System.Speech.Synthesis.SpeechSynthesizer.
Microsoft.Speech.Synthesis.SpeechSynthesizer包含在Microsoft Software (SDK) (Version11)- https://www.microsoft.com/en-us/download/details.aspx?id=27226中
这个版本的合成器没有内存泄漏。
https://stackoverflow.com/questions/10707187
复制相似问题