0

I found this code:

private void PollPixel(Point location, Color color)
{
    while(true)
    {
        var c = GetColorAt(location);

        if (c.R == color.R && c.G == color.G && c.B == color.B)
        {
            DoAction();
            return;
        }
    }
}

But I don't want that return();, I want it to work until I close the program. If I remove that return the program won't work. It will start an infinte loop. I want this program to pay attention to a pixel, then if it changes its color, DoAction will activate a macro. Then it will start paying attention again. How could I do it?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Guilherme Pressutto
  • 785
  • 2
  • 6
  • 18

2 Answers2

0

You can either use Thread.Sleep or use a Timer and add an interval for doing what you wanted. The interval is in milliseconds.

Read the following posts and decide whats the best for you:

  1. Compare using Thread.Sleep and Timer for delayed execution
  2. C# Timer or Thread.Sleep
Community
  • 1
  • 1
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
0

Try:

Task.Factory.StartNew( () => {
// your code here
});

This will create a thread for your method. Do not forget to add a Thread.Sleep(1000) (or with any other value), otherwise you will create a busy loop.

Edit: a more complete sample as per request:

private bool run = true; //set this to false when your program closes
private void StartPollPixel(Point location, Color color)
{
    Task.Factory.StartNew( () => {

       while( run )
       {
           var c = GetColorAt(location);

           if (c.R == color.R && c.G == color.G && c.B == color.B)
           {
               DoAction(); //if you manipulate the UI do not forget to Invoke()
               Thread.Sleep(1000);
           }
       }

    });

}
Mario The Spoon
  • 4,799
  • 1
  • 24
  • 36
  • It actually solves the problem... Care to explain why not? If he wants it to run until his program closes, It needs to run in a seperate thread. – Mario The Spoon May 02 '15 at 06:09
  • 1
    The OP's problem doesn't have anything to do with threading. You can add a thread of course, to avoid locking up the UI thread, but the OP's issue concerns control flow, which you haven't addressed. You haven't even shown how they would incorporate TPL, as you're suggesting, into their code. – Asad Saeeduddin May 02 '15 at 06:12
  • I provided a more complete example. – Mario The Spoon May 02 '15 at 06:18