简体   繁体   English

如何在 c# function 中设置超时?

[英]How can I set a timeout into a c# function?

I've recently created a function into my c# program which exectuses some queries and other stuff, and I was wondering if there exists a way to set a timeout for that function: in particlar I'd like my program to be able to stop if the function hasn't been completely executed after 10 minutes.我最近在我的 c# 程序中创建了一个 function 程序,它执行一些查询和其他东西,我想知道是否有办法为该 ZC1C425268E68385D1AB5074C17A94 设置超时10 分钟后 function 尚未完全执行。 I would also like to know if it is possible to implement this control inside the function itself, so as not to write it every time I call it.我也想知道能不能在function本身内部实现这个控件,免得每次调用都写。

The best way is to let the method take a cancellationToken .最好的方法是让该方法采用cancelToken It needs to check this token frequently and abort if it has been cancelled.它需要经常检查这个令牌,如果它被取消了就中止。 Create a token that cancels after some timeout by creating a cancellationTokenSource: new CancellationTokenSource(timeout) and handing the token it owns to the function.通过创建 cancelationTokenSource: new CancellationTokenSource(timeout)并将其拥有的令牌交给 function,创建一个在超时后取消的令牌。 For long running methods it would be good practice to take a cancellation token and some way to report progress.对于长期运行的方法,最好采用取消令牌和某种方式报告进度。

If there is no way to modify the function an alternative might be something like this:如果没有办法修改 function 替代方法可能是这样的:

    public async Task<(T Result, bool Completed)> RunTimeoutFunction<T>(Func<T> func, TimeSpan timeout)
    {
        var funcTask = Task.Run(func);
        var timeoutTask = Task.Delay(timeout);
        var completedTask = await Task.WhenAny(funcTask, timeoutTask);
        if (completedTask == timeoutTask)
        {
            return (default, false);
        }

        return (funcTask.Result, true);
    }

The obvious downside is that the function will continue to run in the background even after the timeout.明显的缺点是function即使在超时后也会继续在后台运行。 This is however kind of unavoidable unless the function can be cancelled cooperatively.然而,这是不可避免的,除非 function 可以合作取消。 A third alternative would be to put the function in a separate process, then you can safely kill the process after the timeout.第三种选择是将 function 放在一个单独的进程中,然后您可以在超时后安全地终止该进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM