C# 我的SharpDX应用程序内存泄漏

C# 我的SharpDX应用程序内存泄漏,c#,memory,directx,sharpdx,C#,Memory,Directx,Sharpdx,这段代码每100毫秒运行一次。内存使用量一直在增加,直到达到1.5 GB,然后崩溃 void takeScreenShot() { Surface s; s = CaptureScreen(); pictureBox1.Image = new Bitmap(Surface.ToStream(s, ImageFileFormat.Bmp)); s.Dispose(); } public Surface CaptureScreen() { int widt

这段代码每100毫秒运行一次。内存使用量一直在增加,直到达到1.5 GB,然后崩溃

void takeScreenShot()
{
    Surface s;
    s = CaptureScreen(); 
    pictureBox1.Image = new Bitmap(Surface.ToStream(s, ImageFileFormat.Bmp));
    s.Dispose();
}

public Surface CaptureScreen()
{
    int width = Screen.PrimaryScreen.Bounds.Width;
    int height = Screen.PrimaryScreen.Bounds.Height;
    Device device = new Device(new Direct3D(), 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters(width, height));
    DisplayMode disp = device.GetDisplayMode(0);
    Surface s = Surface.CreateOffscreenPlain(device, disp.Width, disp.Height, Format.A8R8G8B8, Pool.Scratch);
    device.GetFrontBufferData(0, s);
    return s;
} 

您每次都在创建一个新设备

您应该只创建一次设备,在启动代码中创建一次,然后继续使用它

此外,我怀疑
Surface.ToStream()
中存在内存泄漏,返回的流可能也需要处理

       var stream = Surface.ToStream(s, ImageFileFormat.Bmp);
       pictureBox1.Image = new Bitmap(stream);
       stream.Dispose();
正如Hans Passant提到的,
位图
也需要处理

您可以通过助手非常轻松地调试SharpDX中的内存泄漏,以便对未发布的COM资源进行诊断。在应用程序开始时设置此变量:

SharpDX.Configuration.EnableObjectTracking = true;
当您的应用程序退出时,它将打印未使用stacktrace正确释放的COM对象的报告。这背后的阶级是


可以调用
ObjectTracker.ReportActiveObjects()
在运行时打印当前使用的资源(即使使用堆栈跟踪)

无法重用
CaptureScreen
方法中的某些对象吗?像
装置
表面
?当它崩溃时会发生什么?您是否收到异常或其他类型的反馈?if(pictureBox1.Image!=null)pictureBox1.Image.Dispose()可能重复@HansPassant
pictureBox1.Image.Dispose()
,但如果不是这样,这也是我的猜测。我可以确认Surface.ToStream()正在泄漏内存,但我如何处理返回的流?请参阅我的编辑,我想您缺少一些基本概念
var
,只是一个编译器关键字,没有“var stream”这样的东西.@Shiro我建议切换到SharpDx,因为它是主动的maintained@thumbmunkeys我试着使用这个和他们的例子,但我得到了一些运行时错误,因为我的图形卡驱动程序(根据一个论坛),我不能让它工作