【发布时间】:2013-09-15 18:05:04
【问题描述】:
我正在创建一个应用程序,我从相机获取实时图像并尝试将其放在 WPF 的图像控制上。但是一段时间后它会开始抛出内存不足的异常。
代码如下:
try
{
imgControl.Dispatcher.Invoke(DispatcherPriority.Normal,
(Action)(() =>
{
using (MemoryStream memory = new MemoryStream())
{
lastImage.Save(memory, ImageFormat.Png);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
ImageSource imageSource = bitmapImage;
imgControl.Source = imageSource;
}
}));
}
catch (Exception ex)
{
//Exception handling
}
这是堆栈跟踪:
at System.Windows.Media.Composition.DUCE.Channel.SyncFlush()
at System.Windows.Interop.HwndTarget.UpdateWindowSettings(Boolean enableRenderTarget, Nullable`1 channelSet)
at System.Windows.Interop.HwndTarget.UpdateWindowPos(IntPtr lParam)
at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
有没有办法可以减少内存消耗并找到解决此内存不足异常的方法?
【问题讨论】:
-
您可以使用缓冲区并以块的形式读取/保存文件
-
可以发一下OOM的stacktrace吗?
-
您发布的代码中似乎没有“泄漏”内存。问题可能来自其他地方。堆栈跟踪会很有帮助。
-
图像可能太大,在堆中。
标签: c# .net wpf memory-management out-of-memory