本文介绍了为操作设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有对象 obj
,它是 3rd 方组件,
I have object obj
which is 3rd party component,
// this could take more than 30 seconds
int result = obj.PerformInitTransaction();
我不知道里面发生了什么.我所知道的是,如果需要更长的时间,它就会失败.
I don't know what is happening inside.What I know is if it take longer time, it is failed.
如何为这个操作设置一个超时机制,这样如果超过30秒我就抛出MoreThan30SecondsException
?
how to setup a timeout mechanism to this operation, so that if it takes more than 30 seconds I just throw MoreThan30SecondsException
?
推荐答案
您可以在单独的线程中运行该操作,然后在线程加入操作上设置超时:
You could run the operation in a separate thread and then put a timeout on the thread join operation:
using System.Threading;
class Program {
static void DoSomething() {
try {
// your call here...
obj.PerformInitTransaction();
} catch (ThreadAbortException) {
// cleanup code, if needed...
}
}
public static void Main(params string[] args) {
Thread t = new Thread(DoSomething);
t.Start();
if (!t.Join(TimeSpan.FromSeconds(30))) {
t.Abort();
throw new Exception("More than 30 secs.");
}
}
}
这篇关于为操作设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!