Home Backend Development C#.Net Tutorial Detailed graphic code explanation of C# 5.0 function Async at a glance

Detailed graphic code explanation of C# 5.0 function Async at a glance

Mar 03, 2017 pm 01:30 PM

It’s been about a month since Microsoft released Async CTP, and everyone is talking about itAsync. If you are already very familiar with Async, then please skip it... If you are like me, you only know a little bit of asynchronous programming, but you feel that the previous asynchronous programming was more troublesome. , then, let us explore together what the next generation of C# will bring to us. (Async CTP also supports VB.)


The example in this article is based on Async CTP SP1 Refresh. Since Async is still in the CTP stage, many things are still being discussed, so maybe wait until C# 5.0 Details will change upon release. However, the general idea and concept should not change much.

Get to the point:

First, to try out the Async function, we need to installVisual Studio 2010 SP1 and Microsoft Visual Studio Async CTP (SP1 Refresh).

Let’s first set up a simple task and look at it separately, synchronous programming, using callbacks to improve asynchronous programming and AsyncProgramming methods, and then let’s analyze them through them, what exactly Async is, and what does it bring to us.

Task:

Create a Windows Form application. When the button is clicked, First display a line of words, for example, start calculation or something to indicate the status, and then calculate from 1 to int.Max/2 is accumulated and the result is displayed.

Synchronization we will do this:

First, write a function to implement the basic algorithm:

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

  #region

 Do things

 

                      

public

  

long

 DoSomething(

int

 n)

 

                     {

 

                          

long

 result = 1;

 

                          

for

 (

int

 i = 1; i <= n; i++)

 

                         {

 

                             result += i;

 

                         }

 

                          

return

 result;

 

                     }

        #endregion

Copy after login


然后,添加一个按钮的Click事件处理程序:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

private

  

void

 btnSync_Click(

object

 sender,

EventArgs

 e)

 

                     {

 

                         lblResult.Text =

"Start to do something . . ."

;

 

                          

long

 value = DoSomething(

int

.MaxValue / 2);

 

                         lblResult.Text = value.ToString();

 

                     }

Copy after login


代码第一行改写Label的字样;第二行调用算法获得结果;第三行把结果输出。看似挺不算的。运行一下,就会发现有两个问题:

  1. 这个算法需要四五秒钟左右的实现时间,并且在这几秒钟的时间里,界面是锁死的,也就是说应用程序就像死了一样,它不接受任何用户操作。(也许我的电脑比较差,呵呵,所以,如果你没有遇到这种情况,请加大输入参数的值,让它算一会儿。)

  1. 我们没有看到Start to do something这一行字。

OK,出现这个现象也是可以理解的,因为我们把大量的运算添加到了UI线程里面了。所以,解决方法就是把它放到外面。我试了一下不用Async,实现的代码如下:

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

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

private

  

void

 btnCallback_Click(

object

 sender,

EventArgs

 e)

 

                     {

 

                         lblResult.Text =

"Start to do something . . ."

;

 

                         Func<

int

,

long

> callBackDelegate = 

this

.DoSomething;

            callBackDelegate.BeginInvoke(

 

                              

int

.MaxValue / 2,

 

                              

new

 AsyncCallback(

 

                             a =>

 

                             {

 

                                 lblResult.Invoke(

new

 MethodInvoker(() =>

 

                                     {

 

                                         lblResult.Text = callBackDelegate.EndInvoke(a).ToString();

 

                                     }));

 

                             }),

 

                              

null

);

 

                     }

Copy after login


如果你觉得这段代码比较晕,那就跳过这一节吧。可能我代码写得不好,大家将就看我简单解释一下,我首先给DoSomething写了一个代理,然后,调用了代理的BeginInvoke方法,把算法放到了其它的Thread中去调用了。这个代理执行完了以后,因为它不会直接返回一个long型的值,而是会去执行一个AsyncCallBack,所以,就在这个Callback里,去调用这个代理的EndInvoke()

 

好吧,且不论代码质量,这个就是有Async之前的一种实现异步的方法。

从这个代码里,我们完全看不到原来代码的影子,我也没有办法像解释同步代码一样解释:第一、第二、第三……有了Async之后呢?呵呵,代码说明一切:

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

38

39

40

41

42

43

44

45

46

47

48

49

50

public

  

Task

<

long

> DoSomethingAsync(

int

 n)

 

                     {

 

                         

return

  

TaskEx

.Run<

long

>(() => DoSomething(n));

 

                     }

  

         

private

  

async

  

void

 btnAsync_Click(

object

 sender, 

EventArgs

 e)

 

                     {

 

                         lblResult.Text = 

"Start do something..."

;

 

                          

var

 x = 

await

 DoSomethingAsync(

int

.MaxValue / 2);

 

                         lblResult.Text = x.ToString();

 

                     }

Copy after login


Three things:

First: Add a file reference: AsyncCtpLibrary.dll. I believe that after Async is officially released, this will appear in the .NET application set.

Second: Encapsulate DoSomething into a Task.

Third: Add some keywords, such as async, such as await.

Let’s take a closer look at the code:

First, I write the return value of the code to be executed asynchronously as Task. This return value actually has three options: void, Task and Task, how to use it specifically, please check Task on MSDNC#4.0 category.

Then, I called the Run method in TaskEx, Pass it a method with a return value of long - that's the algorithm for our task.

If you are interested in studying, you can take a look at Run actually calls Task.Factory. StartNew, and this Start first creates a Task, and then Called its Start method...

Okay, the algorithm is sealed as a task and partially completed.

The second part of the code is easier to explain:

The first line rewrites the words Label; The second line calls the algorithm to get the result; the third line outputs the result. <--This line is copied/ and pasted from the previous text:-)

Haha, let’s take a closer look and compare Sync and Async Code:

##Sync

Async

        private void btnSync_Click(object sender, EventArgs e)
                    {
                        lblResult.Text = 
"Start to do something . . .";
                        
long value = DoSomething(int.MaxValue / 2);
                        lblResult.Text = value.ToString();
                    }

        private async void btnAsync_Click(object sender, EventArgs e)
                    {
                        lblResult.Text = 
"Start do something...";
                        
var x = await DoSomethingAsync(int.MaxValue / 2);
                        lblResult.Text = x.ToString();
                    }

First, we add async to the method name to declare that this is a method with asynchronous calls;

Then, we add a awaitKeywords. Let’s guess what type x is? The answer is long type. With await, even during design, the compiler will automatically convert the type of Task into TType. The code ends here, but what does the new Async

function bring to us? Is it the ability of asynchronous programming? We can also use

Callback

to achieve asynchronousness, and the IAsyncCallback interface should be in .NET 1.1# It has been implemented in ##; the multi-threaded namespace has also existed for a long time; Task was introduced in C# 4.0... I think, Async brings to programmers a code logic-centered and multi-functional Threaded programming. Through the final comparison, we see that the code of

Async

is almost the same as the code of Sync, and the program no longer needs to spend a lot of effort Consider issues such as callbacks, synchronization, etc... This is consistent with the direction that C# has been working hard. Programmers describe more what is done rather than how to do it. Finally, attach the application download and source code, as well as screenshots of the running interface... (Okay, I am not an artist, please forgive me:-)

Click to download the source code

Click on Async

to see Go to the running prompt:

Display the execution result:

The latest and most official Async information is here: ^v^


http://msdn.microsoft.com/Async

The above is the detailed graphic code explanation of Async function in C# 5.0 , for more related content, please pay attention to the PHP Chinese website (www.php.cn)!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Access Modifiers in C# Access Modifiers in C# Sep 03, 2024 pm 03:24 PM

Guide to the Access Modifiers in C#. We have discussed the Introduction Types of Access Modifiers in C# along with examples and outputs.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

C# StringReader C# StringReader Sep 03, 2024 pm 03:23 PM

Guide to C# StringReader. Here we discuss a brief overview on C# StringReader and its working along with different Examples and Code.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

BinaryWriter in C# BinaryWriter in C# Sep 03, 2024 pm 03:22 PM

Guide to BinaryWriter in C#. Here we discuss syntax and explanation, how it works with examples to implement with proper codes.

See all articles