我有一个如下的示例代码,它有逻辑可以在30分钟后取消任务。
Method1调用Method2和Method3,分别需要15分钟和10分钟才能完成。我已经给出了5分钟的缓冲,并将所有执行的超时限制设置为30分钟。
public class Program
{
static void Main()
{
Program p = new Program();
var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(0.5));
var token = tokenSource.Token;
var task = Task.Factory.StartNew(() => {
p.Method1(token);
}, token);
try
{
task.Wait();
}
catch (AggregateException e)
{
Console.WriteLine("Method1 did not finish within 1 mins :" + DateTime.Now);
}
finally
{
tokenSource.Dispose();
}
Console.ReadLine();
}
public bool Method1(CancellationToken token)
{
Console.WriteLine("Inside Method1 :" + DateTime.Now);
Method2(token);
return true;
}
public bool Method2(CancellationToken token)
{
try
{
token.ThrowIfCancellationRequested();
Console.WriteLine("Inside Method2 begin :" + DateTime.Now);
Thread.Sleep(60000); // In the actual code , this line is replaced with the line which executes for more than 1 min.To replicate it, I just made the Thread to sleep.
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();
}
Console.WriteLine("Inside Method2 end :" + DateTime.Now);
return true;
}
catch (Exception ex)
{
Console.WriteLine("Exception in Method2");
return false;
}
}
}
现在我面临的问题是,方法执行的顺序不同于我在整体执行时间超过30分钟时的示例。假设方法2的执行需要更多的时间来完成。
期望值:
内部方法1
内部方法2
方法2中的例外
方法1没有在30分钟内完成
现实:
内部方法1
内部方法2
方法2中的例外
需要进行哪些更改才能使执行流程符合预期。有可能吗?
在这个示例中,我只给出了方法2的示例。实际上,有3-4种方法可以执行一些典型的操作。其中任何一个都可能需要时间来执行。因此,只为Method2设置超时并不能解决问题。
编辑2
我已经删除了旧代码,并替换为答案中建议的代码,以避免任何混淆。这里我所做的是让线程睡眠1分钟,因为超时时间只有30秒。这里发生的事情是,当执行到达线程时。睡眠时,它会等待60秒,然后抛出异常。我希望它在30秒结束后立即抛出异常。