Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...