1. Trang chủ
  2. » Công Nghệ Thông Tin

Lập trình .net 4.0 và visual studio 2010 part 11 potx

6 314 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 6
Dung lượng 152,65 KB

Nội dung

CHAPTER 4  CLR AND BCL CHANGES 72 Garbage Collection in .NET 4.0 So what’s changed then? Prior to .NET 4.0, a concurrent workstation GC could do most but not all of a generation 0 and 1 collection at the same time as a generation 2 collection. The GC was also unable to start another collection when it was in the middle of a collection which meant that only memory in the current segment could be reallocated. In .NET 4.0, however, concurrent workstation GC collection is replaced by background garbage collection. The simple explanation (and GC gets very complex) is that background garbage collection allows another GC (gen 0 and 1) to start at the same time as an existing full GC (gen 0, 1, and 2) is running, reducing the time full garbage collections take. This means that resources are freed earlier and that a new memory segment could be created for allocation if the current segment is full up. Background collection is not something you have to worry aboutit just happens and will make your applications perform more quickly and be more efficient, so it’s yet another good reason to upgrade your existing applications to .NET 4.0. Background collection is not available in server mode GC, although the CLR team has stated they are aiming to achieve this in the next version of the framework. The GC team has also done work to ensure that garbage collection works effectively on up to 128 core machines and improved the GC’s efficiency, reducing the time needed to suspend managed threads For more information and a detailed interview with the GC team, please refer to http://blogs.msdn. com/ukadc/archive/2009/10/13/background-and-foreground-gc-in-net-4.aspx and http://channel9. msdn.com/shows/Going+Deep/Maoni-Stephens-and-Andrew-Pardoe-CLR-4-Inside-Background-GC/. GC.RegisterForFullGCNotification() It is worth noting that from .NET 3.5SP1, the CLR has a method called GC.RegisterForFullGCNotification() that lets you know when a generation 2 or large heap object collection occurs in your applications. You might want to use this information to route users to a different server until the collection is complete, for example. Threading Threading has been tweaked in .NET 4.0, with the thread pool switching to a lock-free data structure (apparently the queue used for work items is very similar to ConcurrentQueue). This new structure is more GC-friendly, faster, and more efficient. Prior to .NET 4.0, the thread pool didn’t have any information about the context in which the threads were created, which made it difficult to optimize (for example, whether one thread depends on another). This situation changes in .NET 4.0 with a new class called Task that provide more information to the thread pool about the work to be performed thus allowing it to make better optimizations. Tasks and other parallel and threading changes are covered in detail in Chapter 5. Globalization Globalization is becoming increasingly important in application development. The .NET 4.0 Framework now supports a minimum of 354 cultures (compared with 203 in previous releasesnow with new support for Eskimos/Inuitsand a whole lot more). A huge amount of localization information is compiled into the .NET Framework. The main problem is that the .NET Framework doesn’t get updated that often, and native code doesn’t use the same localization info. This changes in .NET 4.0 for Windows 7 users because globalization information is read directly from the operating system rather than the framework. This is a good move because it presents a CHAPTER 4  CLR AND BCL CHANGES 73 consistent approach across managed/unmanaged applications. For users not lucky enough to be using Windows 7 (it’s good; you should upgrade), globalization information will be read from the framework itself as per usual. Note that Windows Server 2008 will still use the localized .NET 4.0 store. Globalization Changes in .NET 4.0 There have been a huge number of globalization changes; many of them will affect only a minority of users. For a full list, please refer to http://msdn.microsoft.com/en-us/netframework/dd890508.aspx. I do want to draw your attention to some of the changes in .NET 4.0: • Neutral culture properties will return values from the specific culture that is most dominant for that neutral culture. • Neutral replacement cultures created by .NET 2.0 will not load in .NET 4.0. • Resource Manager will now refer to the user’s preferred UI language instead of that specified in the CurrentUICultures parent chain. • Ability to opt in to previous framework versions’ globalization-sorting capabilities. • zh-HK_stroke, ja-JP_unicod, and ko-KR_unicod alternate sort locales removed. • Compliance with Unicode standard 5.1 (addition of about 1400 characters). • Support added for following scripts: Sundanese, Lepcha, Ol Chiki, Vai, Saurashtra, Kayah Li, Rejang, and Cham. • Some cultures display names changed to follow naming convention guidelines: (Chinese, Tibetan (PRC), French (Monaco), Tamazight (Latin, Algeria), and Spanish (Spain, International Sort). • Parent chain of Chinese cultures now includes root Chinese culture. • Arabic locale calendar data updated. • Culture types WindowsOnlyCultures and FrameworkCultures now obsolete. • CompareInfo.ToString()() and TextInfo.ToString()() will not return locale IDs because Microsoft wants to reduce this usage. • Miscellaneous updates to globalization properties such as currency, date and time formats, and number formatting. • Miscellaneous updates to globalization properties such as currency, date and time formats, and number formatting. TimeSpan Globalized Formatting and Parsing TimeSpan now has new overloaded versions of ToString()(), Parse()(), TryParse()(), ParseExact()(), and TryParseExact()() to support cultural sensitive formatting. Previously, TimeSpan’s ToString() method would ignore cultural settings on an Arabic machine, for example. CHAPTER 4  CLR AND BCL CHANGES 74 Security In previous releases of .NET, the actions code could perform could be controlled using Code Access Security (CAS) policies. Although CAS undoubtedly offered much flexibility, it could be confusing to use and didn’t apply to unmanaged code. In .NET 4.0, security is much simpler. Transparency Model The transparency model divides code into safe, unsafe, and maybe safe code (depending on settings in the host the application is running in). .NET has a number of different types of hosts in which applications can live, such as ASP.NET, ClickOnce, SQL, Silverlight, and so on. Prior to .NET 4.0, the transparency model was used mainly for auditing purposes (Microsoft refers to this as transparency level 1) and in conjunction with code checking tools such as FxCop. The transparency model divides code into three types: • Transparent • Safe critical • Critical Transparent Code Transparent code is safe and verifiable code such as string and math functions that will not do anything bad to users’ systems. Transparent code has the rights to call other transparent code and safe critical code. It might not call critical code. Safe Critical Code Safe critical code is code that might be allowed to run depending on the current host settings. Safe critical code acts as a middle man/gatekeeper between transparent and critical code verifying each request. An example of safe critical code is FileIO functions that might be allowed in some scenarios (such as ASP.NET) but not in others (such as Silverlight). Critical Code Critical code can do anything and calls such as Marshal come under this umbrella. Safe Critical Gatekeeper Transparent code never gets to call critical code directly, but has to go via the watchful eye of safe critical code. Why Does It Matter? If your .NET 4.0 application is running in partial trust, .NET 4.0 will ensure that transparent code can call only other transparent and safe critical code (the same as the Silverlight security model). When there is a call to safe critical code, a permission demand is made that results in a check of permissions allowed by the current host. If your application does not have permissions, a security exception will occur. CHAPTER 4  CLR AND BCL CHANGES 75 Security Changes There are a number of security changes: • Applications that are run from Windows Explorer or network shares run in full trust. This avoids some tediousness because prior to .NET 4.0 local and network applications would run with different permission sets. • Applications that run in a host (for example, ASP.NET, ClickOnce, Silverlight, and SQL CLR) run with the permissions the host grants. You thus need worry only that the host grants the necessary permissions for your application. Partial trust applications running within a host are considered transparent applications (see following) and have various restrictions on them.  NOTE Full trust applications such as ASP.NET application can still call critical code, so they are not considered transparent. • Runtime support has been removed for enforcing Deny, RequestMinimum, RequestOptional, and RequestRefuse permission requests. Note that when you upgrade your applications to use .NET 4.0, you might receive warnings and errors if your application utilizes these methods. As a last resort, you can force the runtime to use legacy CAS policy with the new NetFx40_ LegacySecurityPolicy attribute. For migration options, see http://msdn.microsoft.com/ en-us/library/ee191568(VS.100).aspx.  CAUTION If you are considering using the NetFx40_LegacySecurityPolicy, Shawn Farkas on the Microsoft Security team warned me that “This will have other effects besides just re-enabling Deny , and Request* though, so its use should generally be as a last resort. In general, uses of Deny were a latent security hole, we’ve found that most people tend to need LegacyCasPolicy in order to continue to use the old policy APIs (CodeGroups, etc) before they cut over to the newer sandboxing model.” • For un-hosted code, Microsoft now recommends that security policies are applied by using Software Restriction Policies (SRPs,), which apply to both managed and unmanaged code. Hosted code applications (e.g., ASP.NET and ClickOnce) are responsible for setting up their own policies. SecAnnotate SecAnnotate is a new tool contained in the .NET 4.0 SDK that analyzes assemblies for transparency violations. CHAPTER 4  CLR AND BCL CHANGES 76 APTCA and Evidence I want to highlight two other changes (that probably will not affect the majority of developers): • Allow Partially Trusted Callers Attribute (APTCA) allows code that is partially trusted (for example, web sites) to call a fully trusted assembly and has a new constructor that allows the specification of visibility with the PartialTrustVisibilityLevel enumeration. • A new base class called Evidence has been introduced for all objects to be used that all evidence will derive from. This class ensures that an evidence object is not null and is serializable. A new method has also been added to the evidence list, enabling querying of specific types of evidence rather than iterating through the collection.  NOTE Thanks to Shawn Farakas of the Microsoft security team for assisting me with this section. Monitoring and Profiling .NET 4.0 introduces a number of enhancements that enable you to monitor, debug, and handle exceptions: • .NET 4.0 allows you to obtain CPU and memory usage per application domain, which is particularly useful for ASP.NET applications (see Chapter 10). • It is now possible to access ETW logs (no information available at time of writing) from .NET. • A number of APIs have been exposed for profiling and debugging purposes. • No longer must profilers be attached at application startup; they can be added at any point. These profilers have no impact and can be detached at any time. Native Image Generator (NGen) NGen is an application that can improve the startup performance of managed applications by carrying out the JIT work normally done when the application is accessed. NGen creates processor optimized machine code (images) of your application that are cached. This can reduce application startup time considerably. Prior to .NET 4.0, if you updated the framework or installed certain patches, it was necessary to NGen your application all over again. But no longer; through a process known as “targeted” patching, regenerating images is no longer required. CHAPTER 4  CLR AND BCL CHANGES 77 Native Code Enhancements I will not be covering changes to native code, so I have summarized some of the important changes here: • Support for real-time heap analysis. • New integrated dump analysis and debugging tools. • Tlbimp shared source is available from codeplex (http://clrinterop.codeplex.com/). • Support for 64-bit mode dump debugging has also been added. • Mixed mode 64-bit debugging is now supported, allowing you to transition from managed to native code. Exception Handling Exception handling has been improved in .NET 4.0 with the introduction of the System.Runtime. ExceptionServices namespace, which contains classes for advanced exception handling. CorruptedStateExceptions Many developers (OK, I might have done this, too) have written code such as the following: try { // do something that may fail } catch(System.exception e) { } This is almost always a very naughty way to write code because all exceptions will be hidden. Hiding exceptions you don’t know about is rarely a good thing, and if you do know about them, you should inevitably be handling them in a better way. Additionally, there are some exceptions that should never be caught (even by lazy developers) such as lowdown beardy stuff such as access violations and calls to illegal instructions. These exceptions are potentially so dangerous that it’s best to just shut down the application as quick as possible before it can do any further damage. So in .NET 4.0, corrupted state exceptions will never be caught even if you specify a try a catch block. However, if you do want to enable catching of corrupted state exceptions application-wide (e.g., to route them to an error-logging class), you can add the following setting in your applications configuration file: LegacyCorruptedStateExceptionsPolicy=true This behavior can also be enabled on individual methods with the following attribute: [HandleProcessCorruptedStateExceptions] . CHAPTER 4  CLR AND BCL CHANGES 72 Garbage Collection in .NET 4. 0 So what’s changed then? Prior to .NET 4. 0, a concurrent workstation GC could do most but not all of a generation 0 and 1. framework itself as per usual. Note that Windows Server 200 8 will still use the localized .NET 4. 0 store. Globalization Changes in .NET 4. 0 There have been a huge number of globalization changes;. watchful eye of safe critical code. Why Does It Matter? If your .NET 4. 0 application is running in partial trust, .NET 4. 0 will ensure that transparent code can call only other transparent

Ngày đăng: 01/07/2014, 21:20

TỪ KHÓA LIÊN QUAN