Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

c# - How can I prevent garbage collection from being called when calling ShowDialog on a xaml window?

I have a application that's using a lot of memory, but for now I cannot change this fact. My problem is that I have an operation I'd like to perform and provide a progress dialog but it appears that displaying the xaml progress window is causing GC.Collect to be called 10 times! Any ideas how I can optimize opening my progress window?

According to my Ants Profiler the calls leading up to GC.Collect are

System.Window.ShowDialog() ->
..
..
System.Windows.Media.Imaging.BitmapSource.CreateCachedBitmap ->
SafeMILHandle.UpdateEstimatedSize ->
SafeMILHandleMemoryPressure.ctor ->
MemoryPressure.Add ->
MemoryPressure.ProcessAdd ->
GC.Collect
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is also a solution that would completely disable the bitmap image related memory pressure and subsequent garbage collection. It is more of a hack, but you can read about similar issue here.

typeof(BitmapImage).Assembly.GetType("MS.Internal.MemoryPressure").GetField("_totalMemory", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, Int64.MinValue / 2); 

This way you avoid searching all over your code to find and modify WPF icon initialization. On top of that some controls like System.Windows.Forms.Integration.ElementHost will implicitly add bitmap related memory pressure regardless of how you initialize.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...