I’am having trouble with my While loop, this while loop, needs to be updates whenever something changed in my While loop the last time.
This is my code, it is running in a thread:
private void CheckAllPorts()
{
while (true)
{
MultipleClock = false;
OneClock = false;
NoClock = false;
portCount = 0;
//clear the string list.
MultiplePortNames.Clear();
//create an object searcher and fill it with the path and the query provided above.
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
try
{
foreach (ManagementObject queryObj in searcher.Get())
{
if (queryObj["InstanceName"].ToString().Contains("USB") || queryObj["InstanceName"].ToString().Contains("FTDIBUS"))
{
portCount = searcher.Get().Count;
if (portCount > 1)
{
MultiplePortNames.Add(queryObj["PortName"].ToString());
form1.UpdateListBox(MultiplePortNames);
MultipleClock = true;
}
else if (portCount == 1)
{
MultiplePortNames.Add(queryObj["PortName"].ToString());
form1.UpdateListBox(MultiplePortNames);
OneClock = true;
}
}
else
{
NoClock = true;
form1.UpdateListBox(MultiplePortNames);
}
}
}
catch
{
NoClock = true;
form1.UpdateListBox(MultiplePortNames);
}
Debug.WriteLine("NoClock = " + NoClock);
Debug.WriteLine("OneClock = " + OneClock);
Debug.WriteLine("MultipleClock = " + MultipleClock);
Thread.Sleep(500);
}
}
So if the portCount was 1 last time, and it is this time something else like: 0 or 4, then
it needs to execute this code:
form1.UpdateListBox(MultiplePortNames);
when the portCount was something like 2 last time, and it is also 2 this time, the code shouldn’t be executed.
Does anybody know a solution for my problem?
Apart from the obvious problem with the overall structure of this code (can you tell me when you plan to exit from that while(true)?) and focusing only on your question I think you should change the inner loop in this way
I have added a
lastCountvariable to keep track of the result of the previous loop over the USB port discovery code and changed the inner loop to call the listbox update only at the end of the foreach loop. Don’t know if the xxxClock variables are still of use or not.