【问题标题】:Best way to implement a timeout in a reading process in C#在 C# 中的读取过程中实现超时的最佳方法
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    相关资源
    最近更新 更多