多次更改ImageSource后,WPF C#'System.OutOfMemoryException'

时间:2019-03-11 19:31:21

标签: c# wpf

我有一个列表视图菜单,该菜单将更改网格的背景图像,但是在更改图像大约5-6次后,该程序冻结,并且当我关闭该程序时,错误为System.OutOfMemoryException。这是我正在使用的代码。

 private void ListViewMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        switch (((ListViewItem)((ListView)sender).SelectedItem).Name)
        {
            case "Ground":
                imageMap.Source = new BitmapImage(new Uri(@"\main\1.png", UriKind.Relative));
                break;
            case "Second":
                imageMap.Source = new BitmapImage(new Uri(@"\main\2.png", UriKind.Relative));
                break;
            case "Third":
                imageMap.Source = new BitmapImage(new Uri(@"\main\3.png", UriKind.Relative));
                break;
            case "Fourth":
                imageMap.Source = new BitmapImage(new Uri(@"\main\4.png", UriKind.Relative));
                break;
            case "Fifth":
                imageMap.Source = new BitmapImage(new Uri(@"\main\5.png", UriKind.Relative));
                break;
            case "Sixth":
                imageMap.Source = new BitmapImage(new Uri(@"\main\6.png", UriKind.Relative));
                break;
            case "Seventh":
                imageMap.Source = new BitmapImage(new Uri(@"\main\7.png", UriKind.Relative));
                break;

            default:
                break;
        }
    }

1 个答案:

答案 0 :(得分:-1)

尝试一下:

using System.GC;
...

private void ListViewMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    switch (((ListViewItem)((ListView)sender).SelectedItem).Name)
    {
        case "Ground":
            imageMap.Source = new BitmapImage(new Uri(@"\main\1.png", UriKind.Relative));
            break;
        case "Second":
            imageMap.Source = new BitmapImage(new Uri(@"\main\2.png", UriKind.Relative));
            break;
        case "Third":
            imageMap.Source = new BitmapImage(new Uri(@"\main\3.png", UriKind.Relative));
            break;
        case "Fourth":
            imageMap.Source = new BitmapImage(new Uri(@"\main\4.png", UriKind.Relative));
            break;
        case "Fifth":
            imageMap.Source = new BitmapImage(new Uri(@"\main\5.png", UriKind.Relative));
            break;
        case "Sixth":
            imageMap.Source = new BitmapImage(new Uri(@"\main\6.png", UriKind.Relative));
            break;
        case "Seventh":
            imageMap.Source = new BitmapImage(new Uri(@"\main\7.png", UriKind.Relative));
            break;

        default:
            break;
    }
}