如何为一行c#代码设置超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13513650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:50:11  来源:igfitidea点击:

How to set timeout for a line of c# code

c#timeout

提问by Hossein

Possible Duplicate:
Set timeout to an operation

可能的重复:
为操作设置超时

How can i set timeout for a line of code in c#. For example RunThisLine(SomeMethod(Some Input), TimeSpan.FromSeconds(10))run SomeMethodwith 10 second time out. Thanks in advance.

如何在 C# 中为一行代码设置超时。例如 RunThisLine(SomeMethod(Some Input), TimeSpan.FromSeconds(10))运行SomeMethod10 秒超时。提前致谢。

采纳答案by Carsten

You can use the Task Parallel Library. To be more exact, you can use Task.Wait(TimeSpan):

您可以使用任务并行库。更准确地说,您可以使用 Task.Wait(TimeSpan)

using System.Threading.Tasks;

var task = Task.Run(() => SomeMethod(input));
if (task.Wait(TimeSpan.FromSeconds(10)))
    return task.Result;
else
    throw new Exception("Timed out");

回答by paul

I use something like this (you should add code to deal with the various fails):

我使用这样的东西(你应该添加代码来处理各种失败):

    var response = RunTaskWithTimeout<ReturnType>(
        (Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);


    /// <summary>
    /// Generic method to run a task on a background thread with a specific timeout, if the task fails,
    /// notifies a user
    /// </summary>
    /// <typeparam name="T">Return type of function</typeparam>
    /// <param name="TaskAction">Function delegate for task to perform</param>
    /// <param name="TimeoutSeconds">Time to allow before task times out</param>
    /// <returns></returns>
    private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
    {
        Task<T> backgroundTask;

        try
        {
            backgroundTask = Task.Factory.StartNew(TaskAction);
            backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
        }
        catch (AggregateException ex)
        {
            // task failed
            var failMessage = ex.Flatten().InnerException.Message);
            return default(T);
        }
        catch (Exception ex)
        {
            // task failed
            var failMessage = ex.Message;
            return default(T);
        }

        if (!backgroundTask.IsCompleted)
        {
            // task timed out
            return default(T);
        }

        // task succeeded
        return backgroundTask.Result;
    }

回答by Mo Patel

You can use the IAsyncResult and Action class/interface to achieve this.

您可以使用 IAsyncResult 和 Action 类/接口来实现这一点。

public void TimeoutExample()
{
    IAsyncResult result;
    Action action = () =>
    {
        // Your code here
    };

    result = action.BeginInvoke(null, null);

    if (result.AsyncWaitHandle.WaitOne(10000))
         Console.WriteLine("Method successful.");
    else
         Console.WriteLine("Method timed out.");
}