I have to do a process to read some information and return a result, lamentably the library I use to read base the result in events, and I need a synchronous process to get the result. I made the following code, and it works perfectly, but I have to implement a timeout to throw an exception when the time raised, and this time could be different for different readings.
public class Process
{
private readonly Reader _reader;
public Process()
{
_reader = new Reader();
}
public string Read()
{
string result = null;
ReadEventHandler handler = (sender, e) =>
{
if (!IsDataValid(e.Data)) return;
result = e.Data;
};
_reader.OnRead += handler;
while (result == null)
{
_reader.Read();
Thread.Sleep(1000);
}
_reader.OnRead -= handler;
return result;
}
private bool IsDataValid(string data)
{
//Here I will evaluate the info returned by the reader
return true;
}
}