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

时间:2016-11-25 15:49:59

标签: c# .net timeout synchronous reader

我必须做一个过程来读取一些信息并返回一个结果,可悲的是我用来读取事件中结果的库,我需要一个同步过程来获得结果。我做了以下代码,它完美地运行,但是我必须实现超时以在引发时间时抛出异常,并且对于不同的读数,这个时间可能不同。

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

1 个答案:

答案 0 :(得分:0)

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

相关问题