Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void TestTimeOut()
- {
- var cts = new CancellationTokenSource();
- cts.CancelAfter(5000);
- try
- {
- var task = Task.Run(() => LongRunningOperation(cts.Token));
- task.ContinueWith(t => Console.WriteLine("Operation cancelled"), TaskContinuationOptions.OnlyOnFaulted);
- task.Wait();
- }
- catch (AggregateException e)
- {
- //Handle
- }
- }
- void LongRunningOperation(CancellationToken token)
- {
- CancellationTokenRegistration registration = token.Register(
- () =>
- {
- throw new OperationCanceledException(token);
- });
- using (registration)
- {
- // long running operation here
- }
- }
- static void LongRunningOperation(CancellationToken token)
- {
- TaskCompletionSource<int> tcs1 = new TaskCompletionSource<int>();
- token.Register(() => { tcs1.TrySetCanceled(token); });
- Task.Run(() =>
- {
- // long running operation here
- Thread.Sleep(5000);
- tcs1.TrySetResult(0);
- }, token);
- tcs1.Task.Wait();
- }
Add Comment
Please, Sign In to add comment