我有对象obj
,它是第 3 方组件,
// this could take more than 30 seconds
int result = obj.PerformInitTransaction();
我不知道里面发生了什么。 我所知道的是,如果需要更长的时间,它就会失败。
如何为该操作设置超时机制,以便在超过 30 秒时抛出 MoreThan30SecondsException
?
最佳答案
您可以在单独的线程中运行操作,然后在线程连接操作上设置超时:
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.");
}
}
}
关于c# - 为操作设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2265412/