Threading of the CLR via C #-collaborative cancellation and timeouts

Source: Internet
Author: User

Threading of the CLR via C #-collaborative cancellation and timeouts

Threading of the CLR via C #-collaborative cancellation and timeouts
Collaborative cancellation and timeouts

Collaborative cancellation and timeouts

To create a collaborative cancellation step:

    1. First, create a System.Threading.CancellationTokenSource object.
  
 
  1. public sealed class CancellationTokenSource : IDisposable
  2. {
  3. // 一个引用类型
  4. public void Dispose(); // 释放资源(比如WaitHandle)
  5. public Boolean IsCancellationRequested { get; }
  6. public CancellationToken Token { get; }//通过这个属性获得Token并传递给操作。
  7. public void Cancel(); // 内部调用Cancel并传递false
  8. public void Cancel(Boolean throwOnFirstException);
  9. ...
  10. }
    1. One or more cancellationtoken are obtained through the Cancellationtokensource.token property and passed to the operation.
  
 
  1. public struct CancellationToken
  2. {
  3. // 一个值类型
  4. public static CancellationToken None { get; }
  5. public Boolean IsCancellationRequested{ get; } // 由非通过Task调用的操作调用
  6. public void ThrowIfCancellationRequested(); // 由通过Task调用的操作调用
  7. //CancellationTokenSource 取消时,WaitHandle 会收到信号
  8. public WaitHandle WaitHandle { get; }
  9. public Boolean CanBeCanceled { get; } // 很少使用
  10. public CancellationTokenRegistration Register(Action<Object> callback, Object state,
  11. Boolean useSynchronizationContex); // 未列出更简单的重载版本
  12. }
    1. The Iscancellationrequest property is queried periodically in the method that needs to be canceled.
  
 
  1. internal static class CancellationDemo
  2. {
  3. public static void Go()
  4. {
  5. CancellationTokenSource cts = new CancellationTokenSource();
  6. cts.Token.Register(() => Console.WriteLine("cancel callbace!!!"));
  7. var restration = cts.Token.Register(o => Console.WriteLine("Cancel callback{0}!!!", o), 5, true);
  8. restration.Dispose();
  9. ThreadPool.QueueUserWorkItem(o => Count(cts.Token, 1000));
  10. Console.WriteLine("Press Enter to cancel");
  11. Console.ReadLine();
  12. cts.Cancel();
  13. Console.ReadLine();
  14. }
  15. private static void Count(CancellationToken token, Int32 countTo)
  16. {
  17. for (int count = 0; count < countTo; count++)
  18. {
  19. if (token.IsCancellationRequested)
  20. {
  21. Console.WriteLine("Count is cancelled");
  22. break;
  23. }
  24. Console.WriteLine(count);
  25. Thread.Sleep(200);
  26. }
  27. Console.WriteLine("Count is done");
  28. }
  29. }

PS: If you want to perform an operation that is not allowed to be canceled, you can pass the Cancellationtokensource.none property to the operation.

    1. If required, you can call CancellationToken's Register method to register the callback at the time of cancellation. You can remove the registered callback function by calling its Dispose method by callcellationtakenregistration the method's return value.
    2. You can also link another set of CancellationTokenSource to create a new CancellationTokenSource object.
  
 
  1. var cts1 = new CancellationTokenSource();
  2. cts1.Token.Register(() => Console.WriteLine("cts1 cancelled"));
  3. var cts2 = new CancellationTokenSource();
  4. cts2.Token.Register(() => Console.WriteLine("cts2 canceled"));
  5. //创建一个新的,它在cts1或cts2取消时取消
  6. var linkedcts Span class= "pun" >= cancellationtokensource createlinkedtokensource ( cts1 token cts2 token
  7. linkedCts.Token.Register(() => Console.WriteLine("linkedCts canceled"));
    1. You can also specify the delay time by CancellationTokenSource the constructor or by calling Cancelafter to cancel automatically.
  
 
  1. public sealed class CancellationTokenSource : IDisposable
  2. {
  3. public CancellationTokenSource(Int32 millisecondsDelay);
  4. public CancellationTokenSource(TimeSpan delay);
  5. public void CancelAfter(Int32 millisecondsDelay);
  6. public void CancelAfter(TimeSpan delay);
  7. ...
  8. }


From for notes (Wiz)

Threading of the CLR via C #-collaborative cancellation and timeouts

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.