0

I have some c# experiece, but I'm new to WinForms.

I have a method that takes a screenshot as a BitMap:

public Bitmap GetSreenshot() 
{
    Rectangle bounds = Screen.PrimaryScreen.Bounds;

    Bitmap bmp = new Bitmap(bounds.Width, bounds.Height,
        PixelFormat.Format32bppArgb);

    Graphics gfx = Graphics.FromImage(bmp);

    gfx.CopyFromScreen(bounds.X,
                                   bounds.Y,
                                   0,
                                   0,
                                   bounds.Size,
                                   CopyPixelOperation.SourceCopy);

    return bmp; 
} 

My problem is that I'm using this in a timer with an interval of ~100ms. Every time a screenshot is taken, I can notice that the UI thread is affected (lag when moving the form etc).

Is there any way to generate the screenshot on another thread so that it wont affect the UI? I've read something about BackgroundWorker, is that the way to go? I would appreciate if someone could point me in the right direction here.

Johan
  • 35,120
  • 54
  • 178
  • 293
  • Background worker is one way to go, but you could also look into Task Parallel Library (`Task` and `Task<>`), if .NET 4.0 is available to you. .NET 4.5 also supports the async/await pattern which can be usefull. – TGlatzer Dec 13 '12 at 09:21
  • @Grumbler85 Ok, yes, its available. Any downsides with background workers vs TPL? – Johan Dec 13 '12 at 09:23
  • 1
    Well personally i like the async/await pattern, because you don't have to split up your code into starting and result-processing blocks (bgworker and task<> both need them).. this http://stackoverflow.com/questions/3513432/task-parallel-library-replacement-for-backgroundworker and this http://msmvps.com/blogs/brunoboucard/archive/2010/11/06/parallel-programming-with-c-4-0-part-3.aspx could provide further information – TGlatzer Dec 13 '12 at 09:27

1 Answers1

2

From comment to answer:

Background worker is one way to go, but you could also look into Task Parallel Library (Task and Task<>), if .NET 4.0 is available to you. .NET 4.5 also supports the async/await pattern which can be usefull.

Task parallel library replacement for BackgroundWorker? and this http://msmvps.com/blogs/brunoboucard/archive/2010/11/06/parallel-programming-with-c-4-0-part-3.aspx will provide further information

Community
  • 1
  • 1
TGlatzer
  • 5,815
  • 2
  • 25
  • 46