search
HomeBackend DevelopmentC#.Net TutorialDetailed graphic code explanation of C# 5.0 function Async at a glance

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:

  #region
 Do things

                     
public
 
long
 DoSomething(
int
 n)

                     {

                         
long
 result = 1;

                         
for
 (
int
 i = 1; i <= n; i++)

                         {

                             result += i;

                         }

                         
return
 result;

                     }
        #endregion


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

 
private
 
void
 btnSync_Click(
object
 sender, 
EventArgs
 e)

                     {

                         lblResult.Text = 
"Start to do something . . ."
;

                         
long
 value = DoSomething(
int
.MaxValue / 2);

                         lblResult.Text = value.ToString();

                     }


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

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

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

 

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

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
);

                     }


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

 

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

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

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();

                     }


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
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
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.