2015-02-06 5 views
2

메모리 누수 문제가 있습니다. 내가 Image를 포함하는 ScatterViewItem을 가지고BitmapImage 캐시를 처리하는 방법은 무엇입니까?

public static BitmapSource BitmapImageFromFile(string filepath) 
{ 
    BitmapImage bi = new BitmapImage(); 

    bi.BeginInit(); 
    bi.CacheOption = BitmapCacheOption.OnLoad; //here 
    bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache; //and here 
    bi.UriSource = new Uri(filepath, UriKind.RelativeOrAbsolute); 
    bi.EndInit(); 

    return bi; 
} 

, 소스는이 함수의 BitmapImage입니다 : 누수 여기에서 비롯됩니다.

실제로는 이보다 훨씬 복잡하기 때문에 이미지를 넣을 수는 없습니다. 또한 이미지 파일이 삭제 될 수 있기 때문에 기본로드 옵션을 사용할 수 없으므로 삭제하는 동안 파일에 액세스하는 일부 권한 문제가 발생합니다.

Image을 닫는 ScatterViewItem을 닫으면 문제가 발생합니다. 그러나 캐시 된 메모리 지워지지 않습니다. 그래서 많은 사이클 후에, 메모리 소비는 꽤 큽니다.

Unloaded 기능 중에 image.Source=null 설정을 시도했지만 삭제하지 않았습니다.

언로드하는 동안 어떻게 메모리를 올바르게 지울 수 있습니까?

+0

[C#에서 메모리를 확보하는 올바른 방법은 무엇입니까?] (http://stackoverflow.com/questions/6066200/what-is-the-correct-way-to-free-memory -in-c-sharp) – Izzy

+1

고마워요,하지만 슬픈 것은 GC가 수집하지 못했다는 것입니다. GC.Collect()를 직접 호출해도 수집되지 않았습니다. –

답변

2

나는 대답을 찾았습니다 here. WPF의 버그 인 것 같습니다.

public void Close() 
{ 
    myImage.Source = null; 
    UpdateLayout(); 
    GC.Collect(); 
} 

myImage 때문에이에서 호스팅되는 : 나는 ScatterViewItem 닫기 전에

public static BitmapSource BitmapImageFromFile(string filepath) 
{ 
    var bi = new BitmapImage(); 

    using (var fs = new FileStream(filepath, FileMode.Open)) 
    { 
     bi.BeginInit();     
     bi.StreamSource = fs;     
     bi.CacheOption = BitmapCacheOption.OnLoad; 
     bi.EndInit(); 
    } 

    bi.Freeze(); //Important to freeze it, otherwise it will still have minor leaks 

    return bi; 
} 
나는 또한 호출됩니다 내 자신 닫기 기능을 만들

:

나는 Freeze을 포함하도록 기능 수정 부모가 닫히기 전에 ScatterViewItem, GC.Collect()을 호출해야합니다. 그렇지 않으면 여전히 메모리에 남아있을 것입니다.

관련 문제