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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (72)

我有一个列表视图菜单,它将更改网格的背景图像,但在更改图像约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;
        }
    }
提问于
用户回答回答于

试试这个:

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;
    }
}

扫码关注云+社区

领取腾讯云代金券