The. NET Framework 4.5 has five great features to share

Source: Internet
Author: User


Brief introduction



It's been almost 1 years since the release of. NET 4.5. But with most recent releases from Microsoft, the problem with. NET developers is that developers only know one or two features, and other features just stay on MSDN and exist as simple documents.



For example, when you ask A. NET developers in the. NET Framework kernel, most of them simply say async and wait (at least the people I'm talking to are talking about these features).



It is also difficult to penetrate all the new features. Because these features may not be as interesting as it sounds to the work you are currently developing.



So in this article I want to mention the 5 I like. NET4.5 features in the kernel. Of course, it's probably just my favorite and not yours. But what I do is I think about the bigger when I choose these traits. NET community, I hope I have met this expectation.






Tip: This article does not discuss new features in ASP. NET, WCF, WPF, WWF, etc. Just a new feature about the kernel.



Feature 1: Async and Wait (code developer)



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.



Let's try to figure out what the above declaration means by using the following code. If you understand the process of the following code:


    1. The Static void Main () method is called from the beginning.

    2. Method () generates a task (thread) named LongTask, and the thread waits 10 seconds.

    3. At the same time, after invoking the task, the control goes back to the method () methods to continue executing the remaining code. In other words, as called when multithreaded (Task.run ... ), the LongTask is still running. For example, wait 10 seconds and the remaining code of the method () methods is also executing.


Now in the same scenario, we want the 3rd step to perform differently. We want the control to go back to the method to execute the next code after LongTask () execution is complete. The "async" and "Wait" keywords can help implement the above features.






Here are three key words about the keyword "async" and "Wait" to remember:


    1. Async and wait are a pair of keywords. You can't use them on your own.

    2. Asynchronously applied to a method. The keyword is a flag that says the method will have a wait keyword.

    3. Wait for the keyword to mark where the task resumed execution. So you always find this keyword associated with a task.


Here is a revised version of the code discussed earlier, where we applied async and wait. All other steps are still described earlier, but step 3 will be executed after step 2 is complete. In simple terms, control returns to method () after the task is completed.






Now that you have read the "async" and "Wait" content, let me ask you a question. The above code can also be implemented by task.wait or task.continuewith, so what is the difference? I'll leave this problem to your homework.



Feature 2: Convenient zip compression (zip compression)






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:


    • System.IO.Compression.FileSystem

    • System.IO.Compression


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


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 as shown.






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.


try
{
  var regEx = new Regex(@”^(\d+)+$”, RegexOptions.Singleline, TimeSpan.FromSeconds(2));
  var match = regEx.Match(“123453109839109283090492309480329489812093809x”);
}
catch (RegexMatchTimeoutException ex)
{
  Console.WriteLine(“Regex Timeout”);
}


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.


using System.Runtime;

// Call the Setprofilerroot and Startprofile method
ProfileOptimization.SetProfileRoot(@"D:\ProfileFile");

ProfileOptimization.StartProfile("ProfileFile");


IMPORTANT: ASP. NET 4.5 and Silverlight 5 apps support Profileoptimization by default. So the code above is not written in these techniques.



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



  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.


CultureInfo cul = new CultureInfo(strCulture);
Thread.CurrentThread.CurrentCulture = cul;
Thread.CurrentThread.CurrentUICulture = 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");

CultureInfo.DefaultThreadCurrentCulture = culture;


  Array supports more than 2GB capacity



I'm not sure what scenario we'll need for a 2GB container. So I personally don't know where we're going to use this feature. If I ever needed such a large container I would break it down into smaller parts. But I'm sure there's a good reason to enable this feature in the framework.



  The console supports Unicode encoding



I leave this feature outside the scope of the discussion because very few people work with console programs. I've seen people use the console for academic purposes. In summary, we now have Unicode encoding support for the console app.



  Reference


    • Http://msdn.microsoft.com/en-us/library/ms171868.aspx

    • Mr Sukesh Marla's exciting article ASP. 4.5 new Features


When you are free, be sure to check out my website www.questpond.com about. NET4.5 interview asked and answer, I have a lot of efforts in this area.





Related Article

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.