在C#中的阅读过程中实现超时的最佳方法



我必须执行一个过程来读取一些信息并返回结果,这是我用来读取事件中结果的库,我需要同步过程才能获得结果。我制作了以下代码,它运行得很好,但是我必须实现超时以在筹集时间时投掷例外,而对于不同的读数可能会有所不同。

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;
    }
}

为什么不使用任务并设置超时?查看此链接:https://blogs.msdn.microsoft.com/pfxteam/2011/11/11/crafting-a-task-task timeoutafter-method/

最新更新