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 Copy after login |
然后,添加一个按钮的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(); } Copy after login |
代码第一行改写Label的字样;第二行调用算法获得结果;第三行把结果输出。看似挺不算的。运行一下,就会发现有两个问题:
这个算法需要四五秒钟左右的实现时间,并且在这几秒钟的时间里,界面是锁死的,也就是说应用程序就像死了一样,它不接受任何用户操作。(也许我的电脑比较差,呵呵,所以,如果你没有遇到这种情况,请加大输入参数的值,让它算一会儿。)
我们没有看到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 ); } Copy after login |
如果你觉得这段代码比较晕,那就跳过这一节吧。可能我代码写得不好,大家将就看我简单解释一下,我首先给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(); } 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
Then, I called the Run
If you are interested in studying, you can take a look at Run
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) |
private async void btnAsync_Click(object sender, EventArgs e) |
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
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 codeClick 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 (m.sbmmt.com)!