c# – 如何为此代码添加超时

前端之家收集整理的这篇文章主要介绍了c# – 如何为此代码添加超时前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Asynchronously wait for Task<T> to complete with timeout12个
我试图为此代码添加超时,但因为我是新手,我无法弄清楚,
  1. Task.Factory.StartNew(() =>
  2. {
  3. Aspose.Words.Document doc = new Aspose.Words.Document(inputFileName);
  4. doc.Save(Path.ChangeExtension(inputFileName,".pdf"));
  5. });

此外,我希望主线程在此等待,直到它超时5分钟或完成.

编辑

或者我可以使用取消令牌,如果是,那么如何:(?

解决方法

您可以使用Task.Delay创建一个新任务并使用Task.WhenAny:
  1. Task delayedTask = Task.Delay(TimeSpan.FromMinutes(5));
  2. Task workerTask = Task.Factory.StartNew(() =>
  3. {
  4. Aspose.Words.Document doc = new Aspose.Words.Document(inputFileName);
  5. doc.Save(Path.ChangeExtension(inputFileName,".pdf"));
  6. });
  7.  
  8. if (await Task.WhenAny(delayedTask,workerTask) == delayedTask)
  9. {
  10. // We got here because the delay task finished before the workertask.
  11. }
  12. else
  13. {
  14. // We got here because the worker task finished before the delay.
  15. }

您可以使用Microsoft.Bcl.Async向.NET 4.0添加async-await功能

编辑:

当您使用VS2010时,您可以使用Task.Factory.ContinueWheAny:

  1. Task.Factory.ContinueWhenAny(new[] { delayedTask,workerTask },task =>
  2. {
  3. if (task == delayedTask)
  4. {
  5. // We got here if the delay task finished before the workertask.
  6. }
  7. else
  8. {
  9. // We got here if the worker task finished before the delay.
  10. }
  11. });

编辑2:

由于Task.Delay在.NET 4.0中不可用,您可以使用扩展方法自己创建它:

  1. public static class TaskExtensions
  2. {
  3. public static Task Delay(this Task task,TimeSpan timeSpan)
  4. {
  5. var tcs = new TaskCompletionSource<bool>();
  6. System.Timers.Timer timer = new System.Timers.Timer();
  7. timer.Elapsed += (obj,args) =>
  8. {
  9. tcs.TrySetResult(true);
  10. };
  11. timer.Interval = timeSpan.Milliseconds;
  12. timer.AutoReset = false;
  13. timer.Start();
  14. return tcs.Task;
  15. }
  16. }

猜你在找的C#相关文章