0

每一秒,我都会使用以下代码捕获我的屏幕。前 40/50 次有效,之后我InvalidArgumentException在第一行和第三行代码中得到了一个。

Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(bmpScreenshot);
g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
bmpScreen = bmpScreenshot;
4

2 回答 2

3

可能您需要处理一些对象。

仅从显示的代码很难判断,但我的猜测是您没有正确处理对象并且内存不足。我确信Graphics应该处置对象,并且当您完成位图时可能也需要处置它。根据错误捕获的设置方式,如果您吞下内存不足异常并继续执行,则不会实例化不适合可用内存的新对象,并且它们的构造函数将返回 null。如果您随后将 null 传递给不想接收 null 的方法,InvalidArgumentException则很可能会导致结果。

于 2015-04-10T18:24:51.523 回答
0

尝试将 Disposable 对象包装在using语句中。我能够使用以下代码重现您的问题:

public static void Main()
{
    var i = 1;

    while (true)
    {
        var screenSize = Screen.PrimaryScreen.Bounds.Size;

        try
        {                
            var bmpScreenshot = new Bitmap(screenSize.Width, screenSize.Height);
            var g = Graphics.FromImage(bmpScreenshot);
            g.CopyFromScreen(0, 0, 0, 0, screenSize);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception ignored: {0}", e.Message);
        }
        finally
        {
            Console.WriteLine("Iteration #{0}", i++);
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
    }
}

通过使用 using 语句包装一次性用品,问题不再发生:

public static void Main()
{
    var i = 1;

    while (true)
    {
        var screenSize = Screen.PrimaryScreen.Bounds.Size;

        try
        {                
            using (var bmpScreenshot = new Bitmap(screenSize.Width, screenSize.Height))
            using (var g = Graphics.FromImage(bmpScreenshot))
            {
                g.CopyFromScreen(0, 0, 0, 0, screenSize);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception ignored: {0}", e.Message);
        }
        finally
        {
            Console.WriteLine("Iteration #{0}", i++);
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
    }
}
于 2015-04-10T18:49:29.000 回答