在返回一个值的函数实现了超时函数、实现了

由网友(孤灯一盏)分享简介:我有一个函数调用了读或写一个串行端口请求,然后返回读取值。我使用Commstudio EX preSS(我采取从Commstudio类),但它的超时功能不会出现在所有的工作,所以我想实现我自己的超时。目前我有时设置请求读取或写入到端口的计时器,并且如果计时器熄灭,回调关闭引起异常的连接。我想有定时器的回调抛出一个异常,...

我有一个函数调用了读或写一个串行端口请求,然后返回读取值。我使用Commstudio EX preSS(我采取从Commstudio类),但它的超时功能不会出现在所有的工作,所以我想实现我自己的超时。目前我有时设置请求读取或写入到端口的计时器,并且如果计时器熄灭,回调关闭引起异常的连接。我想有定时器的回调抛出一个异常,但该异常需要传播了通过在呼唤着原来的读/写功能,因此以这种方式,它的工作线程,但我觉得这是混乱的,有必须有一个更好的办法做到我想做的。

I have a function that calls out a read or write request on a serial port and then returns the value that was read. I am using Commstudio express (I'm implementing a class from Commstudio) , but it's timeout features don't appear to work at all, so I'm trying to implement my own timeout. Currently I have a timer that is set upon request to read or write to the port, and if the timer goes off, the callback closes the connection causing an exception. I tried to have the callback of the timer throw an exception, but the exception needs to be propagated up through the thread that was calling the original read/write function, so in this way, it works, but I feel like it's messy and there must be a better way to do what I want.

推荐答案

下面是一个通用的解决方案,使您可以包装在一个超时的任何方法:

Here is a generic solution that allows you to wrap any method in a timeout:

http://kossovsky.net/index.php/2009/07/csharp-how-to-limit-method-execution-time/

它使用接受以毫秒为单位超时而不是手动有用的Thread.join 超载使用定时器。我唯一​​会做不同的是调剂成功的标志和结果值相匹配的TryParse图案,如下所示:

It uses the useful Thread.Join overload that accepts a timeout in milliseconds rather than manually using timers. The only thing I would do differently is swap the success flag and result value to match the TryParse pattern, as follows:

public static T Execute<T>(Func<T> func, int timeout)
{
    T result;
    TryExecute(func, timeout, out result);
    return result;
}

public static bool TryExecute<T>(Func<T> func, int timeout, out T result)
{
    var t = default(T);
    var thread = new Thread(() => t = func());
    thread.Start();
    var completed = thread.Join(timeout);
    if (!completed) thread.Abort();
    result = t;
    return completed;
}

这是你将如何使用它:

And this is how you would use it:

var func = new Func<string>(() =>
    {
        Thread.Sleep(200);
        return "success";
    });
string result;
Debug.Assert(!TryExecute(func, 100, out result));
Debug.Assert(result == null);
Debug.Assert(TryExecute(func, 300, out result));
Debug.Assert(result == "success");

您也可以添加接受行动代替的

阅读全文

相关推荐

最新文章