Search code examples
c#infinite-loop

How to handle an Inifinite Loop in C#


I have a small program that's supposed to sample some value from a device connected via USB. I want to sample the device every 0.5 seconds - so I created a loop that repeats itself every 500miliseconds and works pretty well:

while(_bool)
{
    Sample_USB_Device();
    Present_Data_To_Screen();
}

My question is this:

How can I control the _bool variable? When I run the code the GUI freezes and I don't have any access to it. I tried to used Threads, but I can't send the data back from the thread to the GUI (or I don't know how).


Solution

  • You can use a Timer to run your code at a specified interval, instead of using a loop. The timer can be enabled or disabled.