开发者

CheckPixelColor on thread

I have a function that checks the color at specified positions (using GetPixel from winapi) for very short period of time(50 ms). Right now I use a timer on the form to call that function every 50 ms, but my application freezes like hell.

How do I make it in a separate thread th开发者_如何学JAVAat repeats itself to infinity so that it doesn't freeze the user interface?


I'd have to recommend tackling the perf problem before bringing out the thread canon. 50 milliseconds is a looong time. This sample code had no effect on interactivity nor made a blip on the cpu load, even though it isn't optimized:

    Random rand = new Random();

    private void timer1_Tick(object sender, EventArgs e) {
        using (var bmp = new Bitmap(1, 1)) {
            using (var gr = Graphics.FromImage(bmp)) {
                gr.CopyFromScreen(rand.Next(800), rand.Next(600), 0, 0, new Size(1, 1));
                Console.WriteLine(bmp.GetPixel(0, 0).ToString());
            }
        }
    }


Since UI is STA thread you can't access it froma thread different from the one that created it. Or you can by using "Control.Invoke" but in this case it runs upon the message loops so I think you will experience some delay as well.


Use a Background Worker, and use a timer to call backgroundworker.runasync();. http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜