我正在尝试使用以下代码加载图片:
void LoadPictures(int s)
{
grdScene.Children.Clear();
TabControl tab = new TabControl();
for (int i = s; i <= s+3; i++)
{
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap("C:\\img\\" + i + ".png");
TabItem tabItem = new TabItem();
tabItem.Header = "Scene " + i;
var bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
Image image = new Image();
image.Source = bitmapSource;
tabItem.Content = image;
tab.Items.Add(tabItem);
}
grdScene.Children.Add(tab);//grdScene is Grid
}
它工作正常,但每次我运行此方法时,内存都会增加。然后我尝试将所有项目设置为null
,但没有成功。这是代码:
foreach (var child in grdScene.Children)
{
TabControl tab1 = (TabControl)child;
foreach (TabItem item in tab1.Items)
{
Image img = (Image)item.Content;
img = null;
}
tab1 = null;
}
我试过GC.Collect()
但没有任何改变。我应该怎么做才能解决这个问题?