设置超时操作 [英] Set timeout to an operation

查看:111
本文介绍了设置超时操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象 OBJ 这是第三方组件,

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.");
        }
    }
}

这篇关于设置超时操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆