Five new features of the. NET Framework 4.5

Source: Internet
Author: User

The Framework 4.5 has developed several projects and wants to look at the cross-platform in VS 2015. But as if the new features of the 4.5 kernel are not yet understood, let's look at the new features of the 4.5 kernel, 4.5. What new features are in the NET Framework kernel? Seems to be not very clear , at most is what we often say async and await can also use a bit, most people also know this .... Believe that this framework certainly has more than one feature

Reference:
Https://msdn.microsoft.com/zh-cn/library/ms171868.aspx

It's a little short today, just look at the new features that are better in 4.5. (Most of the content from the online, I just sort of study) nonsense not much to say, start:

Feature 1: Async and wait (async and await)

This feature has been boasted over and over and each. NET preachers all talk about it. But it's still my favorite and you'll know why it's only a few lines from here.

Async and wait are tokens, and they mark where the control should revert to the code when the task (thread) ends.

Async (C # Reference)
https://msdn.microsoft.com/zh-cn/library/vstudio/hh156513 (v=vs.110). aspx

Asynchronous programming using Async and Await (C # and Visual Basic)
https://msdn.microsoft.com/zh-cn/library/vstudio/hh191443 (v=vs.110). aspx

Let's start with an analog common long-time operation method:

      Static voidMain (string[] args)            {Method (); Console.WriteLine ("Main Thread");        Console.readkey (); }        Static voidMethod () {Task.run (NewAction (LongTask)); Console.WriteLine ("New Thread"); }             Static voidLongTask () {System.Threading.Thread.Sleep (10000); Console.WriteLine ("LongTask"); }

Operation Result:

Look at the effect of using the keyword:

       Static voidMain (string[] args)            {Method (); Console.WriteLine ("Main Thread");        Console.readkey (); }        Static Async voidMethod () {awaitTask.run (NewAction (LongTask)); Console.WriteLine ("New Thread"); }        Static voidLongTask () {System.Threading.Thread.Sleep ( +); Console.WriteLine ("LongTask"); }

Operation Result:

See the results of the output is very clear!

Feature 2: Convenient zip compression (zip compression)

Reference: https://msdn.microsoft.com/Zh-cn/library/hh485707.aspx/html

Zip is one of the most accepted file formats. The ZIP format is supported by almost all operating systems with some built-in names.

In the Windows operating system, it is implemented as a "compressed file" name.
In the Mac operating system, it is implemented as the name of the document utility.
Now in. NET we do not have built-in support for performing zip compression. Many developers have practical third-party components such as "DotNetZip". In. NET4.5, the zip attribute is built into the framework itself, to the System.IO.Compression namespace.

The first step involves referencing two namespaces:

Next, the following two namespaces are referenced:

using System.IO.Compression;

If you want to compress files from a folder you can call the Createfromdirectory function as shown below.

Zipfile.createfromdirectory (@ "D:\data"@ "D:\data.zip"  True, Encoding.UTF8);

If you want to unzip, you can call the Extracttodirectory function as shown in the code below.

Zipfile.extracttodirectory (@"D:\data.zip"@ "D:\data\unzip" );
Attribute 3: Regular expression timeout (timeout)

Regular expressions are always the preferred way to do validation. If you're new to regular expressions, look at regular expressions, and I'll explain how regular expressions are executed. But because of the typical logical parsing of regular expressions, it is exposed to Dos attacks. Let's try to understand what I said just now.

As an example, consider such a regular expression-"^ (\d+) $". This regular expression indicates that there can be only numbers. You can also see the regular expression symbol graph, which indicates how the regular expression will be evaluated. Now let's assume that you want to validate "123456X". This will have 6 paths

But if we add one more number, there will be 7 paths. In other words, as the character length increases, the regular expression will take more time to execute. In other words, the evaluation time is linearly proportional to the length of the character.

Now let's change the previously defined regex from "^ (\d+) $" to "^ (\d+) +$". If you look at the regular expression symbol graph it will be quite complex. If we try to verify "123456X" Now, there will be 32 paths. If you add one more character, the number of paths will increase to 64.

In other words, the time overhead in the above regular expression is exponentially related to the number of characters.

Now, you might want to ask, is that important? The linear ascent evaluation time can be exploited by hackers for DOS (denial of service) attacks. They can deploy a long and long enough string to keep your app hanging forever.

The appropriate workaround for this problem is to set the time-out on the execution of the regular expression. The good news is that in. NET4.5 you can define a timeout property as shown in the following code. So if you receive any malicious string, the app does not always execute in the loop.

      Static voidMain (string[] args) {            Try            {                varRegEx =NewSystem.Text.RegularExpressions.Regex (@"^ (\d+) +$", System.Text.RegularExpressions.RegexOptions.Singleline, Timespan.fromseconds (2)); varMatch = Regex.match ("123453109839109283090492309480329489812093809x"); }            Catch(System.Text.RegularExpressions.RegexMatchTimeoutException ex) {Console.WriteLine ("Regex Timeout"); }        }    

The result of the operation is obvious:

Feature 4: Tuning profile (improves startup performance)

We all know that. NET code is a semi-compiled format. At run time, the JIT (just-in-time) compiler executes and transforms this semi-compiled IL code into machine-native code. One of the biggest complaints about JIT is that when the. NET application is first executed, it runs slowly because the JIT is busy converting the IL code to the machine code.

In order to reduce this startup time, there is something called "Optimization Profile" in. NET4.5. A configuration file is simply a simple file that records the list of methods that the app needs to start running. So when the app starts, the background JIT executes and starts converting the IL code of these methods to machine/native language.

This background JIT compiles the startup method on multiple processors to further reduce startup time. Also note that you need a multi-core processor for configuration file optimization. If you do not have multicore processors then this setting will be ignored.

In order to create the "config file" file, you first need to introduce the System.Runtime namespace. You can then invoke the Setprofileroot and StartProfile methods of the static class Profileoptimization. Now when the app starts the background JIT, it will read the configuration file and compile the startup method in the background to reduce the startup time.

Reference: Https://msdn.microsoft.com/zh-cn/library/system.runtime.profileoptimization (v=vs.110). aspx

Using// call the setprofilerroot and StartProfile method Profileoptimization.setprofileroot (@ "C: \profilefile"); Profileoptimization.startprofile ("profilefile");
Feature 5: Garbage collection (garbage background cleanup)

Garbage collection in. NET application is a really heavy task. When it is an ASP. NET application, it becomes more onerous. Asp. NET application runs on the server, many clients send requests to the server to generate the object load, so that garbage collection does try to clean up unwanted objects.

In. NET4.0, when garbage collection runs cleanup, all application threads are paused. In the you can see that we have 3 application threads executing. There are two garbage collections running on different threads. A garbage collection thread corresponds to a logical processor. The application threads now run and perform their tasks, and they also create action objects as they are executed by these application threads.

At some point in time, the background garbage collection run begins to clean up. When these garbage collections start to clean up, they pause all the application threads. This makes the server/application unresponsive at that moment.

To overcome these problems, server garbage collection was introduced. A thread that runs in the background is created more in the server garbage collection mechanism. This thread runs in the background and cleans up 2 generations of objects (about garbage collection 0, 1, and 2 generations of video) to reduce the overhead of the primary garbage collection thread. Because of the execution of the dual garbage collection threads, the main application threads are rarely paused, which in turn increases application throughput. In order to use server garbage collection, we need to use the Gcserver XML tag and set it to true.

<configuration>   <runtime>      <gcserver enabled="true"/>   </runtime></configuration>

Three other features worth exploring
1. Setting the culture of the default application domain
In the previous version of the. NET if I want to set the culture then I need to set it in each thread. The following sample program demonstrates the pain of the thread level setting culture. This is the real pain when we have a lot of multithreaded applications.

New== cul;

In 4.5 We can set the culture at the application domain level and all threads in this application domain will inherit the culture. Here's how to implement the Defaultthreadcurrentculture sample code.

CultureInfo Culture = cultureinfo.createspecificculture ("fr-fr"= culture;

2. Array supports more than 2GB capacity

3. The console supports Unicode encoding

Five new features of the. NET Framework 4.5

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.