{"id":1162,"date":"2023-03-21T16:04:20","date_gmt":"2023-03-21T09:04:20","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=1162"},"modified":"2023-03-21T16:04:29","modified_gmt":"2023-03-21T09:04:29","slug":"csharp-cancellationtokensource","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-cancellationtokensource\/","title":{"rendered":"C# CancellationTokenSource"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use C# <code>CancellationTokenSource<\/code> to cancel an asynchronous operation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Cancellation is cooperative<\/h2>\n\n\n\n<p>In .NET, cancellation is cooperative. It means that when you request to cancel an asynchronous operation, it&#8217;s up to the code running that operation to check whether cancellation has been requested and stop running if it has.<\/p>\n\n\n\n<p>Also, cancellation is not something that is automatically enforced by .NET, but rather a mechanism that you have to implement manually in your code using a <code>CancellationToken<\/code> object.<\/p>\n\n\n\n<p>In other words, if you want an asynchronous operation to be cancellable, in the operation, you need to explicitly check for cancellation requests using the <code>IsCancellationRequested<\/code> property of the <code>CancellationToken<\/code> object, and stop running if it returns <code>true<\/code>.<\/p>\n\n\n\n<p>To create an <code>CancellationToken<\/code>, you use the <code>CancellationTokenSource<\/code> class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to use CancellationTokenSource class<\/h2>\n\n\n\n<p>Here are the steps for using the <code>CancellationTokenSource<\/code> class:<\/p>\n\n\n\n<p>First, create a new  <code>CancellationTokenSource<\/code> object that can be used to generate a cancellation token:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">var<\/span> cts = <span class=\"hljs-keyword\">new<\/span> CancellationTokenSource();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, pass the cancellation token to an asynchronous operation:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">AsyncOperation(cts.Token);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, check for cancellation requests in the asynchronous operation and stop running if the cancellation has been requested:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-function\">Task&lt;T&gt; <span class=\"hljs-title\">AsyncOperation<\/span>(<span class=\"hljs-params\">CancellationToken cancellationToken<\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">while<\/span> (!cancellationToken.IsCancellationRequested)\n    {\n        <span class=\"hljs-comment\">\/\/ Do some work...<\/span>\n    }\n\n    <span class=\"hljs-comment\">\/\/ The operation was cancelled...<\/span>\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Finally, signal cancellation using the Cancel() method of the <code>CancellationTokenSource<\/code> object:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">cts.Cancel();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">C# CancellationTokenSource example<\/h2>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">using<\/span> <span class=\"hljs-keyword\">static<\/span> System.Console;\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">static<\/span> List&lt;<span class=\"hljs-keyword\">int<\/span>&gt; <span class=\"hljs-title\">Square<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">int<\/span> max, CancellationToken token<\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">var<\/span> result = <span class=\"hljs-keyword\">new<\/span> List&lt;<span class=\"hljs-keyword\">int<\/span>&gt;();\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">int<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; max; i++)\n    {\n        Thread.Sleep(<span class=\"hljs-number\">500<\/span>);\n\n        <span class=\"hljs-keyword\">if<\/span> (token.IsCancellationRequested)\n        {\n            WriteLine(<span class=\"hljs-string\">\"Cancellation requested!!!\"<\/span>);\n            token.ThrowIfCancellationRequested();\n            <span class=\"hljs-keyword\">break<\/span>;\n        }\n\n        <span class=\"hljs-keyword\">var<\/span> square = i * i;\n\n        WriteLine(square);\n        result.Add(square);\n    }\n    <span class=\"hljs-keyword\">return<\/span> result;\n}\n\nCancellationTokenSource cts = <span class=\"hljs-keyword\">new<\/span>();\n\n<span class=\"hljs-keyword\">var<\/span> task = Task.Run(() =&gt; Square(<span class=\"hljs-number\">10<\/span>, cts.Token));\ntask.ContinueWith((t) =&gt;\n{\n    <span class=\"hljs-keyword\">var<\/span> squares = t.Result;\n    WriteLine(<span class=\"hljs-string\">\"The square numbers are\"<\/span>);\n    <span class=\"hljs-keyword\">foreach<\/span> (<span class=\"hljs-keyword\">var<\/span> square <span class=\"hljs-keyword\">in<\/span> squares)\n    {\n        Write(<span class=\"hljs-string\">$\"<span class=\"hljs-subst\">{square}<\/span> \"<\/span>);\n    }\n}, TaskContinuationOptions.OnlyOnRanToCompletion);\n\n\nWriteLine(<span class=\"hljs-string\">\"Press 'c' to cancel.\"<\/span>);\n<span class=\"hljs-keyword\">while<\/span> (<span class=\"hljs-literal\">true<\/span>)\n{\n    <span class=\"hljs-keyword\">var<\/span> keyInfo = ReadKey(<span class=\"hljs-literal\">true<\/span>);\n    <span class=\"hljs-keyword\">if<\/span> (keyInfo.KeyChar == <span class=\"hljs-string\">'c'<\/span>)\n    {\n        <span class=\"hljs-keyword\">if<\/span> (task.Status == TaskStatus.Running)\n        {\n            cts.Cancel();\n            WriteLine(<span class=\"hljs-string\">\"Canceling the task...\"<\/span>);\n            <span class=\"hljs-keyword\">break<\/span>;\n        }\n    }\n    <span class=\"hljs-comment\">\/\/ quit if the task has been completed<\/span>\n    <span class=\"hljs-keyword\">if<\/span> (task.Status == TaskStatus.RanToCompletion)\n    {\n        <span class=\"hljs-keyword\">break<\/span>;\n    }\n}\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">Press 'c' to cancel.\n0\n1\n4\n9\n16\n25\nCanceling the task...<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, create a <code>CancellationTokenSource<\/code> object.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">CancellationTokenSource cts = <span class=\"hljs-keyword\">new<\/span>();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, create a new task that executes the <code>Square()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">var<\/span> task = Task.Run(() =&gt; Square(<span class=\"hljs-number\">10<\/span>, cts.Token));<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>Square()<\/code> method returns a list of square numbers based on the argument. For example, if you pass 10 to the <code>Square()<\/code> method, it&#8217;ll return a list of square numbers of 1, 2, 3, &#8230; 9, which are 2, 4, 9, &#8230; 81. Also, we pass a <code>CancellationToken<\/code> to the <code>Square()<\/code> method.<\/p>\n\n\n\n<p>Third, define the <code>Square()<\/code> method that returns a list of square numbers. The <code>Square()<\/code> method uses the <code>CancellationToken<\/code> object to check if the cancellation has been requested. If yes, it calls <code>token.ThrowIfCancellationRequested()<\/code> method to raise an <code>OperationCanceledException<\/code> and exit the loop.<\/p>\n\n\n\n<p>Fourth, create a continuation that runs only if the task is running to the completion:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">task.ContinueWith((t) =&gt;\n{\n    <span class=\"hljs-keyword\">var<\/span> squares = t.Result;\n    WriteLine(<span class=\"hljs-string\">\"The square numbers are\"<\/span>);\n    <span class=\"hljs-keyword\">foreach<\/span> (<span class=\"hljs-keyword\">var<\/span> square <span class=\"hljs-keyword\">in<\/span> squares)\n    {\n        Write(<span class=\"hljs-string\">$\"<span class=\"hljs-subst\">{square}<\/span> \"<\/span>);\n    }\n}, TaskContinuationOptions.OnlyOnRanToCompletion);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Fifth, create a loop that checks if the user presses the letter <code>c<\/code> and sends a cancellation using the <code>Cancel()<\/code> method of the <code>CancellationTokenSource<\/code> object and exit the loop. Also, if the task status is <code>RanToCompletion<\/code>, then exit the loop:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">WriteLine(<span class=\"hljs-string\">\"Press 'c' to cancel.\"<\/span>);\n<span class=\"hljs-keyword\">while<\/span> (<span class=\"hljs-literal\">true<\/span>)\n{\n    <span class=\"hljs-keyword\">var<\/span> keyInfo = ReadKey(<span class=\"hljs-literal\">true<\/span>);\n    <span class=\"hljs-keyword\">if<\/span> (keyInfo.KeyChar == <span class=\"hljs-string\">'c'<\/span>)\n    {\n        <span class=\"hljs-keyword\">if<\/span> (task.Status == TaskStatus.Running)\n        {\n            cts.Cancel();\n            WriteLine(<span class=\"hljs-string\">\"Canceling the task...\"<\/span>);\n            <span class=\"hljs-keyword\">break<\/span>;\n        }\n    }\n    <span class=\"hljs-comment\">\/\/ quit if the task has been completed<\/span>\n    <span class=\"hljs-keyword\">if<\/span> (task.Status == TaskStatus.RanToCompletion)\n    {\n        <span class=\"hljs-keyword\">break<\/span>;\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use C# <code>CancellationTokenSource<\/code> to cancel an asynchronous operation executed by a task.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1162\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-cancellationtokensource\/\"\n\t\t\t\tdata-post-title=\"C# CancellationTokenSource\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1162\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-cancellationtokensource\/\"\n\t\t\t\tdata-post-title=\"C# CancellationTokenSource\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn how to use C# CancellationTokenSource to cancel an asynchronous operation.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":760,"menu_order":7,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1162","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1162","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/comments?post=1162"}],"version-history":[{"count":4,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1162\/revisions"}],"predecessor-version":[{"id":1166,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1162\/revisions\/1166"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/760"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=1162"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}