SHARE
TWEET

Task with timeout

a guest Feb 3rd, 2017 185 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             var program = new Program();
  6.             program.Test().Wait();
  7.  
  8.             Console.WriteLine("Press enter to quit.");
  9.             Console.ReadLine();
  10.         }
  11.  
  12.         public async Task Test()
  13.         {
  14.             await DoWithTimeout(() =>
  15.             {
  16.                 Console.WriteLine("Starting main action...");
  17.                 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(7));
  18.                 Console.WriteLine("Finishing main action");
  19.             },
  20.             () => Console.WriteLine("Timeout action is invoked"),
  21.             TimeSpan.FromSeconds(5));
  22.         }
  23.  
  24.         public async Task DoWithTimeout(Action action, Action timeoutAction, TimeSpan timeout)
  25.         {
  26.             var cancellatinSource = new CancellationTokenSource();
  27.  
  28.             var task = Task.Run(action, cancellatinSource.Token);
  29.  
  30.             if (await Task.WhenAny(task, Task.Delay(timeout)) != task)
  31.             {
  32.                 cancellatinSource.Cancel();
  33.                 timeoutAction();
  34.             }
  35.         }
  36.     }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top