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
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

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 Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),