【发布时间】:2017-04-10 01:34:39
【问题描述】:
我必须做一个过程来读取一些信息并返回一个结果,可悲的是我用来读取事件结果的库,我需要一个同步过程来获取结果。我编写了以下代码,它运行良好,但我必须实现超时以在时间引发时抛出异常,并且对于不同的读数,这个时间可能会有所不同。
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;
}
}
【问题讨论】:
标签: c# .net timeout synchronous reader