我有一个函数可以在串行端口上调用读取或写入请求,然后返回读取的值。我正在使用 Commstudio express(我正在实现 Commstudio 的一个类),但它的超时功能似乎根本不起作用,所以我正在尝试实现我自己的超时。目前我有一个定时器,根据请求设置为读取或写入端口,如果定时器关闭,回调将关闭导致异常的连接。我试图让定时器的回调抛出异常,但异常需要通过调用原始读/写函数的线程向上传播,所以这样,它可以工作,但我觉得它很乱而且有一定是做我想做的事情的更好方法。
最佳答案
这是一个通用的解决方案,允许您在超时中包装任何方法:
http://kossovsky.net/index.php/2009/07/csharp-how-to-limit-method-execution-time/
它使用有用的 Thread.Join接受以毫秒为单位的超时而不是手动使用计时器的重载。我唯一会做的不同是交换成功标志和结果值以匹配 TryParse模式,如下:
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;
}
这就是您将如何使用它:
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");
关于c# - 在返回值的函数上实现超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1370811/