简体   繁体   English

在 C# 中规定的时间后停止行执行

[英]Stop a line execution after a stipulated amount of time in C#

I have a Windows service, developed in C#, which does some calculation on data at equal intervals of time say 30 mins.我有一个用 C# 开发的 Windows 服务,它以相等的时间间隔对数据进行一些计算,比如 30 分钟。 It fetches the data from database and calls a method CalcData() which does some business logic calculations.它从数据库中获取数据并调用一个方法 CalcData() 来进行一些业务逻辑计算。

class Program
    {
        static void Main(string[] args)
        {
            try
            {
                AutoCalExecution ae = new AutoCalExecution();
                ae.FetchData();
                ae.CalData();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);                
            }
            Console.ReadLine();
        }
 }

 class AutoCalExecution
{
    public void FetchData()
    {
        // fetch data from db
    }

    public void CalData()
    {
        line1;
        line2;
        line3;
        line4; // this line has som expression which actually does the calculation. 
        line5;
    }  
}

I have given the template of the code which I'm using.我已经给出了我正在使用的代码模板。 In CalData() , line4 is where the calculation is happening.CalData() ,第 4 行是进行计算的地方。 The calculation typically takes 10 mins to be done.计算通常需要 10 分钟才能完成。 So line4 is executed for 10mins.所以 line4 执行了 10 分钟。

There are some scenarios where the calculation might take more than 10 mins.在某些情况下,计算可能需要 10 分钟以上。 In that case I want to cancel the execution and go to line5 after certain amount of time, say 15 mins.在这种情况下,我想取消执行并在一定时间后转到第 5 行,例如 15 分钟。

To summarize I want to set a timeout time for line4 for 15 mins(which can be configured based in requirement), If it doesn't finish with in 15 mins, it has to stop and come to line5.总而言之,我想将第 4 行的超时时间设置为 15 分钟(可以根据需要进行配置),如果在 15 分钟内没有完成,则必须停止并转到第 5 行。

 public void CalData()
    {
        line1;
        line2;
        line3;
        if ( set time to 15 mins exceeds){
            line4; // this line has some expression which actually does the calculation.    
        }
        else 
        {
            Log (Line4 execution did not complete in stipulated time);
        }
        line5;
    }

How do I set that condition in C#?如何在 C# 中设置该条件?

Update更新

This is something I tried:这是我尝试过的:

var task = Task.Run(() => CalData());
                        if (task.Wait(TimeSpan.FromMinutes(Convert.ToDouble(timeout))))
                        {
                            if (task.Result)
                            {
                                log.Info("Completed");
                            }
                            else
                            {
                                log.Error("Not successful");                                
                            }
                        }

But the problem here is I want line5 to get executed in this method if line 4 doesn't finish.但这里的问题是,如果第 4 行未完成,我希望第 5 行在此方法中执行。 Is there a way I can write this similar code for a piece of code/snippet, instead of whole method?有没有办法可以为一段代码/片段而不是整个方法编写类似的代码?

I think you want something like this:我想你想要这样的东西:

var work = Task.Run(() => line4);
if (work.Wait(TimeSpan.FromMinutes(10)))
{
      // Work completed within the timeout
}
else
{
     // Work did not complete within the timeout
}

Note that this will not actually stop the 'DoWork' code from running, it will continue on a worker thread until it is done.请注意,这实际上不会停止“DoWork”代码的运行,它会在工作线程上继续运行,直到完成。 Also note that using 'Wait' risks deadlocks if used improperly, see Don't Block on Async Code .另请注意,如果使用不当,使用 'Wait' 可能会导致死锁,请参阅Don't Block on Async Code

If you actually want to cancel the processing you should give DoWork a cancellationToken and make the processing abort when the token is cancelled.如果您确实想取消处理,您应该给 DoWork 一个取消令牌,并在取消令牌时中止处理。 There are also solutions to abort a running thread, but this is not recommended .也有中止正在运行的线程的解决方案, 但不推荐这样做

Make line4 into a task.使line4成为一项任务。

Make the task cancellable by a cancellation token.使任务可通过取消令牌取消。

Use a cancellation token which cancels itself after 10mins (configured time).使用在 10 分钟(配置时间)后自行取消的取消令牌。

https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.cancelafter?view=netframework-4.8 https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.cancelafter?view=netframework-4.8

https://binary-studio.com/2015/10/23/task-cancellation-in-c-and-things-you-should-know-about-it/ https://binary-studio.com/2015/10/23/task-cancellation-in-c-and-things-you-should-know-about-it/

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

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