Home Backend Development C#.Net Tutorial C# 5.0 introduces two keywords-async and await

C# 5.0 introduces two keywords-async and await

Jun 23, 2017 pm 04:28 PM
.net async await asynchronous programming

C# 5.0 introduces two keywords async and await. These two keywords help us simplify the implementation code of asynchronous programming to a great extent, and the tasks in TPL have a great relationship with async and await

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

private async void button1_Click(object sender, EventArgs e)

        {

            var length = AccessWebAsync();

 

            // 这里可以做一些不依赖回复的操作

            OtherWork();

 

            this.textBox1.Text += String.Format("\n 回复的字节长度为:  {0}.\r\n", await length);

            this.textBox2.Text = Thread.CurrentThread.ManagedThreadId.ToString();

        }

 

        private async Task<long> AccessWebAsync()

        {

            MemoryStream content = new MemoryStream();

 

            // 对MSDN发起一个Web请求

            HttpWebRequest webRequest = WebRequest.Create("http://msdn.microsoft.com/zh-cn/") as HttpWebRequest;

            if (webRequest != null)

            {

                // 返回回复结果

                using (WebResponse response = await webRequest.GetResponseAsync())

                {

                    using (Stream responseStream = response.GetResponseStream())

                    {

                        await responseStream.CopyToAsync(content);

                    }

                }

            }

 

            this.textBox3.Text = Thread.CurrentThread.ManagedThreadId.ToString();

            return content.Length;

        }

 

        private void OtherWork()

        {

            this.textBox1.Text += "\r\n等待服务器回复中.................\n";

        }

Copy after login

async is a synchronous execution program, while await plays the role of dividing fragments and suspending the caller. It does not create new threads. According to the analysis of the master:

The first part of the code and the later part of the code where the await keyword appears are executed synchronously (that is, they are executed on the calling thread, which is the GUI thread, so there is no problem of cross-thread access to controls), the key point of await The code snippet is executed on a thread pool thread.

In the above code, methods such as GetResponseAsync encapsulated by FCL are called so as not to block the current UI thread. await does not create a new thread, but as far as here, the await expression does create The new thread - GetResponseAsync does so much that it creates the illusion of superficial synchronization. I have written an article before
C#async and await asynchronous programming study notes

The await keyword is closely related to Task. It can be seen from its specific return value that the deeper await It should be equivalent to the continuewith function of task. Therefore, using the async & await keywords to achieve asynchronous implementation must either call the asynchronous method encapsulated by FCL, or we can call task ourselves to create a new thread to share the tasks of the UI thread to prevent the UI thread. block.

The above is the detailed content of C# 5.0 introduces two keywords-async and await. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Remove duplicate values ​​from PHP array using regular expressions Remove duplicate values ​​from PHP array using regular expressions Apr 26, 2024 pm 04:33 PM

How to remove duplicate values ​​from PHP array using regular expressions: Use regular expression /(.*)(.+)/i to match and replace duplicates. Iterate through the array elements and check for matches using preg_match. If it matches, skip the value; otherwise, add it to a new array with no duplicate values.

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

What is programming for and what is the use of learning it? What is programming for and what is the use of learning it? Apr 28, 2024 pm 01:34 PM

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

Asynchronous and non-blocking technology in Java exception handling Asynchronous and non-blocking technology in Java exception handling May 01, 2024 pm 05:42 PM

Asynchronous and non-blocking techniques can be used to complement traditional exception handling, allowing the creation of more responsive and efficient Java applications: Asynchronous exception handling: Handling exceptions in another thread or process, allowing the main thread to continue executing, avoiding blocking. Non-blocking exception handling: involves event-driven exception handling when an I/O operation goes wrong, avoiding blocking threads and allowing the event loop to handle exceptions.

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Unleash Your Inner Programmer: C for Absolute Beginners Unleash Your Inner Programmer: C for Absolute Beginners Oct 11, 2024 pm 03:50 PM

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

See all articles