{"id":829,"date":"2023-03-09T15:03:50","date_gmt":"2023-03-09T08:03:50","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=829"},"modified":"2023-03-21T08:30:15","modified_gmt":"2023-03-21T01:30:15","slug":"csharp-async-await","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-async-await\/","title":{"rendered":"C# async\/await"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the C# <code>async<\/code>\/<code>await<\/code> keywords for asynchronous programming.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to C# async\/await keywords<\/h2>\n\n\n\n<p>The following method reads a text file asynchronously and outputs its contents on the console:<\/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\">class<\/span> <span class=\"hljs-title\">Program<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">ShowFileContents<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span> filename<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> task = File.ReadAllLinesAsync(filename);\n\n        task.ContinueWith(t =&gt;\n        {\n            <span class=\"hljs-keyword\">var<\/span> lines = t.Result;\n            <span class=\"hljs-keyword\">foreach<\/span> (<span class=\"hljs-keyword\">var<\/span> line <span class=\"hljs-keyword\">in<\/span> lines)\n            {\n                Console.WriteLine(line);\n            }\n        });\n\n    }\n\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Main<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        ShowFileContents(<span class=\"hljs-string\">\"C:\\\\temp\\\\readme.txt\"<\/span>);\n        Console.Read();\n    }\n}<\/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>How it works.<\/p>\n\n\n\n<p>First, define the <code>ShowFileContents()<\/code> method that takes a string parameter <code>filename<\/code>. The <code>filename <\/code>parameter specifies the path to the file to be read.  <\/p>\n\n\n\n<p>The <code><code>ShowFileContents()<\/code><\/code> method works as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code><code>File.ReadAllLinesAsync<\/code>()<\/code> method reads the file contents asynchronously and returns a <code>Task&lt;string[]&gt;<\/code> object. <\/li>\n\n\n\n<li>To show the contents of the file after <code><code>File.ReadAllLinesAsync<\/code>()<\/code> method completes, we use the <code><code>ContinueWith()<\/code><\/code> method. Inside the method, we get all the lines of the file in the <code>t.Result<\/code> property, which is an array of strings.<\/li>\n\n\n\n<li>The method iterates through the lines using a <code><a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-foreach\/\">foreach<\/a><\/code> loop and displays each line to the console.<\/li>\n<\/ul>\n\n\n\n<p>Second, define the <code>Main()<\/code> method as the main entry point of the program. <\/p>\n\n\n\n<p>The <code>Main()<\/code> method uses the <code>ShowFileContents()<\/code> method to read the <code>readme.txt<\/code> file from the <code>C:\\temp<\/code> directory and display its contents to the console.<\/p>\n\n\n\n<p>The program works fine. But the code is quite verbose and somewhat difficult to follow. To make it more simple, C# introduces the <code>async\/await<\/code> keywords.<\/p>\n\n\n\n<p>When a method is marked with the <code>async<\/code> keyword, it contains asynchronous operations which are executed on a separate thread. This allows the method to return immediately without blocking the calling thread.<\/p>\n\n\n\n<p>The <code>async<\/code> methods need to have an <code>await<\/code> keyword in their body. The <code>await<\/code> keyword waits for the completion of an asynchronous operation before continuing the current execution. <\/p>\n\n\n\n<p>Also, you can use the <code>await<\/code> keyword to wait for a <code><a href=\"https:\/\/csharptutorial.net\/csharp-concurrency\/csharp-task\/\">Task<\/a><\/code> or <code>Task&lt;T&gt;<\/code> object. The <code>await<\/code> keyword pauses the <code>async<\/code> method until the asynchronous operation completes and resumes the execution from where it left off.<\/p>\n\n\n\n<p class=\"note\">Notice that the <code>await<\/code> keyword is only valid inside an <code>async<\/code> method.<\/p>\n\n\n\n<p>The following example converts the above program to the one that uses the <code>async\/await<\/code> keywords.<\/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\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Program<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">async<\/span> Task <span class=\"hljs-title\">ShowFileContents<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span> filename<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> lines = <span class=\"hljs-keyword\">await<\/span> File.ReadAllLinesAsync(filename);\n\n        <span class=\"hljs-keyword\">foreach<\/span> (<span class=\"hljs-keyword\">var<\/span> line <span class=\"hljs-keyword\">in<\/span> lines)\n        {\n            Console.WriteLine(line);\n        }\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">async<\/span> Task <span class=\"hljs-title\">Main<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">await<\/span> ShowFileContents(<span class=\"hljs-string\">\"C:\\\\temp\\\\readme.txt\"<\/span>);\n        Console.Read();\n    }\n}\n<\/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>How it works.<\/p>\n\n\n\n<p>First, mark the <code><code>ShowFileContentsAsync<\/code><\/code> using the <code>async<\/code> keyword. It indicates that the method contains asynchronous operations. By convention, an async method has the <code>Async<\/code> suffix.<\/p>\n\n\n\n<p>Second, use the <code>await<\/code> keyword to wait for the method <code><code><code><code><code>File.ReadAllLinesAsync<\/code><\/code><\/code>()<\/code><\/code> to complete and get the results as an array of strings. <\/p>\n\n\n\n<p>Behind the scenes, the <code><code><code>File.ReadAllLinesAsync<\/code><\/code><\/code> is executed in a separate thread and pauses the <code><code>ShowFileContentsAsync()<\/code><\/code> method. Once the <code><code><code><code><code>File.ReadAllLinesAsync<\/code><\/code><\/code>()<\/code><\/code> completes, it resumes the execution of the <code><code>ShowFileContentsAsync()<\/code><\/code> method.<\/p>\n\n\n\n<p>Third, use a <code><a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-foreach\/\">foreach<\/a><\/code> loop to display each line in the lines array to the console.<\/p>\n\n\n\n<p>Finally, mark the <code>Main()<\/code> method as an <code>async<\/code> method and use the <code>await<\/code> keyword to wait for the <code>ShowFileContentsAsync()<\/code> method to complete.<\/p>\n\n\n\n<p>As you can see, the <code>async\/await<\/code> keyword simplifies the code for asynchronous programming.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the <code>async<\/code> keyword to mark a method that contains asynchronous operations.<\/li>\n\n\n\n<li>Use the <code>await<\/code> keyword inside an <code>async<\/code> method to await for a <code>Task<\/code> or <code>Task&lt;T&gt;<\/code>.<\/li>\n\n\n\n<li>The <code>await<\/code> keyword pauses the <code>async<\/code> method, runs the asynchronous operation in a separate thread, and resumes the execution where it left off.<\/li>\n\n\n\n<li>Always use <code>async <\/code>and <code>await <\/code>together.<\/li>\n\n\n\n<li>Always return a <code>Task<\/code> from an async method.<\/li>\n\n\n\n<li>Always <code>await<\/code> an async method to validate the asynchronous operation.<\/li>\n\n\n\n<li>Do use <code>async<\/code> and <code>await<\/code> all the way up the chain.<\/li>\n\n\n\n<li>Do not use <code>async void<\/code> unless it&#8217;s an event handler.<\/li>\n\n\n\n<li>Do not block an asynchronous operation by calling the <code>Result<\/code> or <code>Wait()<\/code> of a <code>Task<\/code>.<\/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=\"829\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-async-await\/\"\n\t\t\t\tdata-post-title=\"C# async\/await\"\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=\"829\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-async-await\/\"\n\t\t\t\tdata-post-title=\"C# async\/await\"\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 the async\/await keywords for asynchronous programming.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":760,"menu_order":6,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-829","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/829","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=829"}],"version-history":[{"count":5,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/829\/revisions"}],"predecessor-version":[{"id":1158,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/829\/revisions\/1158"}],"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=829"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}