.Net Core中的长时间运行动作超时

时间:2019-01-23 05:40:18

标签: c# multithreading .net-core timeout

如何为可能长时间运行的动作lambda设置超时?我尝试将动作包装在任务中,然后使用取消令牌强制执行超时,但无济于事。

    public void LongRunningTask()
    {
        ExecuteSafely(() => //do something );
    }

    private void ExecuteSafely(Action action)
    {
        try
        {
            action();
        }
        catch
        {
            // just don't crash 
        }
    }

根据第一个答案的新实现:

public void Information<T>(string messageTemplate, T propertyValue)
{
    ExecuteSafely(() => _logger.Information(messageTemplate, propertyValue));
}        

private void ExecuteSafely(Action action)
{
    try
    {
        var cts = new CancellationTokenSource();
        cts.CancelAfter(new TimeSpan(0, 0, 1));

        try
        {
            Task.Run(action, cts.Token).Wait();
        }
        catch (TaskCanceledException e)
        {
            System.Diagnostics.Debug.WriteLine(e.ToString());
            //here you know the task is cancelled due to timeout
        }
    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.WriteLine(e.ToString());
        // just don't crash 
    }
}

仅当我进入Task.Run时此方法才能正常工作,但当我跨步或使其运行时则无法正常工作。也许将lambda传递给操作存在一些关闭问题?

1 个答案:

答案 0 :(得分:0)

您应该使用CancellationTokenSource

    void Execute(Action action, TimeSpan timeout)
    {
        var cts = new CancellationTokenSource();
        cts.CancelAfter(timeout);

        try
        {
            Task.Run(action, cts.Token).Wait();
        }
        catch (TaskCanceledException e)
        {
            //here you know the task is cancelled due to timeout
        }
    }