I'm working on a Problem on an existing Project. We want to read an ADC-value and normally we use there a fire-and-forget concept. We ask for the value and after the value is read an event is raised. However now I have to implement a function, which returns a value directly. My idea was to solve this Problem with polling.
public class Information
{
public delegate void NewADCValueArrived(double newValue);
private event NewADCValueArrived newAdcValue;
private double getADCValueDirectly()
{
double value = -1;
NewADCValueArrived handler = delegate(double newValue)
{
value = newValue;
};
newAdcValue += handler;
askFornewValues(); //Fire and forget
timeout = 0;
while(value != -1 && timeout <100)
{
timeout++;
Thread.sleep(1); //Want to avoid this!! because sleeping for 1 ms is very inaccurate
}
newAdcValue -= handler;
if (value != -1)
{
return value;
}
else
{
throw Exception("Timeout");
}
}
}
The problem now is, that I want to avoid polling. Because often the response is even faster than 1 ms and I want to finish the function as fast as possible. Do you have a better idea to solve this Problem?
In the c#-Documentation I found some information about WaitHandlers but I was not able to integrate them into my program. (https://msdn.microsoft.com/en-us/library/system.threading.waithandle)