0

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;
    }
}
krlzlx
  • 5,752
  • 14
  • 47
  • 55
Josbel Luna
  • 2,574
  • 3
  • 17
  • 25

1 Answers1

0

Why don't you use a Task and set a timeout? Check out this link: https://blogs.msdn.microsoft.com/pfxteam/2011/11/10/crafting-a-task-timeoutafter-method/