c# - 为操作设置超时

标签 c# multithreading timeout

我有对象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/

相关文章:

c# - 第一次重大部署

c# - 使用 OpenXML 按工作表名称读取 excel

.net - 接受大文件的迷你服务器组件

C++ Vector 是线程安全的吗?多线程

xml - ColdFusion 超时错误

c# - 为什么我不能从 C# 中的子类访问 protected 方法?

c# - 为 JWT 生成 key ?

线程退出 while 循环后的 android 守护进程线程

batch-file - 批处理 : How to prompt for input and continue if timed out?

java - java中如何使用循环超时?