The new features and improvements are described in the following sections:
Common Language Runtime (CLR)
Base Class Libraries
Common Language Runtime (CLR)
The following sections describe new features in security, parallel computing, performance and diagnostics, dynamic language runtime, and other CLR-related technologies.
The .NET Framework 4.0 provides simplifications, improvements, and expanded capabilities in the security model. For more information, see Security Changes in the .NET Framework 4.
The .NET Framework 4.0 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new Parallel and Task classes, and other related types, support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax. For more information, see Parallel Programming in the .NET Framework.
Performance and Diagnostics
In addition to the following features, the .NET Framework 4.0 provides improvements in startup time, working set sizes, and faster performance for multithreaded applications.
You can now access the Event Tracing for Windows (ETW) events for diagnostic purposes to improve performance. For more information, see the following topics:
Performance Monitor (Perfmon.exe) now enables you to disambiguate multiple applications that use the same name and multiple versions of the common language runtime loaded by a single process. This requires a simple registry modification. For more information, see Performance Counters and In-Process Side-By-Side Applications.
Code contracts let you specify contractual information that is not represented by a method’s or type’s signature alone. The new System.Diagnostics.Contracts namespace contains classes that provide a language-neutral way to express coding assumptions in the form of pre-conditions, post-conditions, and object invariants. The contracts improve testing with run-time checking, enable static contract verification, and documentation generation.
The applicable scenarios include the following:
- Perform static bug finding, which enables some bugs to be found without executing the code.
- Create guidance for automated testing tools to enhance test coverage.
- Create a standard notation for code behavior, which provides more information for documentation.
With lazy initialization, the memory for an object is not allocated until it is needed. Lazy initialization can improve performance by spreading object allocations evenly across the lifetime of a program. You can enable lazy initialization for any custom type by wrapping the type inside a System..::.Lazy<(Of <(T>)>) class.
Dynamic Language Runtime
The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework. In addition, several new classes that support the .NET Framework infrastructure are added to the System.Runtime.CompilerServices namespace. For more information, see Dynamic Language Runtime Overview.
In-Process Side-by-Side Execution
In-process side-by-side hosting enables an application to load and activate multiple versions of the common language runtime (CLR) in the same process. For example, you can run applications that are based on the .NET Framework 2.0 SP1 and applications that are based on .NET Framework 4.0 in the same process. Older components continue to use the same CLR version, and new components use the new CLR version. For more information, see Hosting Changes in the .NET Framework 4.
New interoperability features and improvements include the following:
- You no longer have to use primary interop assemblies (PIAs). Compilers embed the parts of the interop assemblies that the add-ins actually use, and type safety is ensured by the common language runtime.
- You can use the System.Runtime.InteropServices..::.ICustomQueryInterfaceinterface to create a customized, managed code implementation of theIUnknown::QueryInterface method. Applications can use the customized implementation to return a specific interface (except IUnknown) for a particular interface ID.
In the .NET Framework 4.0, you can attach profilers to a running process at any point, perform the requested profiling tasks, and then detach. For more information, see the [IClrProfiling::AttachProfiler]IClrProfiling Interface::AttachProfiler Method method.
The .NET Framework 4.0 provides background garbage collection; for more information, see the entry So, what’s new in the CLR 4.0 GC? in the CLR Garbage Collector blog.
Covariance and Contravariance
Several generic interfaces and delegates now support covariance and contravariance. For more information, see Covariance and Contravariance in the Common Language Runtime.
Base Class Libraries
The following sections describe new features in collections and data structures, exception handling, I/O, reflection, threading, and Windows registry.
Collections and Data Structures
Enhancements in this area include the new System.Numerics..::.BigInteger structure, theSystem.Collections.Generic..::.SortedSet<(Of <(T>)>) generic class, and tuples.
The new System.Numerics..::.BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.
SortedSet Generic Class
The new System.Collections.Generic..::.SortedSet<(Of <(T>)>) class provides a self-balancing tree that maintains data in sorted order after insertions, deletions, and searches. This class implements the new System.Collections.Generic..::.ISet<(Of <(T>)>) interface.
The System.Collections.Generic..::.HashSet<(Of <(T>)>) class also implements theISet<(Of <(T>)>) interface.
A tuple is a simple generic data structure that holds an ordered set of items of heterogeneous types. Tuples are supported natively in languages such as F# and IronPython, but are also easy to use from any .NET Framework language such as C# and Visual Basic. The ..NET Framework 4.0 adds eight new generic tuple classes, and also aTuple class that contains static factory methods for creating tuples.
The .NET Framework 4.0 class library contains the newSystem.Runtime.ExceptionServices namespace, and adds the ability to handle corrupted state exceptions.
Corrupted State Exceptions
The CLR no longer delivers corrupted state exceptions that occur in the operating system to be handled by managed code, unless you apply theHandleProcessCorruptedStateExceptionsAttribute attribute to the method that handles the corrupted state exception.
Alternatively, you can add the following setting to an application’s configuration file:
The key new features in I/O are efficient file enumerations, memory-mapped files, and improvements in isolated storage and compression.
File System Enumeration Improvements
New enumeration methods in the Directory and DirectoryInfo classes returnIEnumerable<(Of <(T>)>) collections instead of arrays. These methods are more efficient than the array-based methods, because they do not have to allocate a (potentially large) array and you can access the first results immediately instead of waiting for the complete enumeration to occur.
There are also new methods in the static File class that read and write lines from files by using IEnumerable<(Of <(T>)>) collections. These methods are useful in LINQ scenarios where you may want to quickly and efficiently query the contents of a text file and write out the results to a log file without allocating any arrays.
The new System.IO.MemoryMappedFiles namespace provides memory mapping functionality, which is available in Windows. You can use memory-mapped files to edit very large files and to create shared memory for inter-process communication. The newSystem.IO..::.UnmanagedMemoryAccessor class enables random access to unmanaged memory, similar to how System.IO..::.UnmanagedMemoryStream enables sequential access to unmanaged memory.
Isolated Storage Improvements
Partial-trust applications, such as Windows Presentation Framework (WPF) browser applications (XBAPs) and ClickOnce partial-trust applications, now have the same capabilities in the .NET Framework as they do in Silverlight. The default quota size is doubled, and applications can prompt the user to approve or reject a request to increase the quota. The System.IO.IsolatedStorage..::.IsolatedStorageFile class contains new members to manage the quota and to make working with files and directories easier.
The compression algorithms for the System.IO.Compression..::.DeflateStream andSystem.IO.Compression..::.GZipStream classes have improved so that data that is already compressed is no longer inflated. This results in much better compression ratios. Also, the 4-gigabyte size restriction for compressing streams has been removed.
The .NET Framework 4.0 provides the capability to monitor the performance of your application domains.
Application Domain Resource Monitoring
Until now, there has been no way to determine whether a particular application domain is affecting other application domains, because the operating system APIs and tools, such as the Windows Task Manager, were precise only to the process level. Starting with the .NET Framework 4.0, you can get processor usage and memory usage estimates per application domain.
Application domain resource monitoring is available through the managed AppDomainclass, native hosting APIs, and event tracing for Windows (ETW). When this feature has been enabled, it collects statistics on all application domains in the process for the life of the process.
64-bit View and Other Registry Improvements
Windows registry improvements include the following:
- Ability to specify a 32-bit or 64-bit view of the registry with theMicrosoft.Win32..::.RegistryView enumeration when you open base keys.
- the new Microsoft.Win32..::.RegistryOptions enumeration, which lets you specify a volatile registry key that does not persist after the computer restarts.
General threading improvements include the following:
- The new Monitor..::.Enter(Object, Boolean%) method overload takes a Boolean reference and atomically sets it to true only if the monitor is successfully entered.
- You can use the Thread..::.Yield method to have the calling thread yield execution to another thread that is ready to run on the current processor.
The following sections describe new threading features.
Unified Model for Cancellation
The .NET Framework 4.0 provides a new unified model for cancellation of asynchronous operations. The new System.Threading..::.CancellationTokenSource class is used to create a CancellationToken that may be passed to any number of operations on multiple threads. By calling Cancel()()() on the token source object, the IsCancellationRequestedproperty on the token is set to true and the token’s wait handle is signaled, at which time any registered actions with the token are invoked. Any object that has a reference to that token can monitor the value of that property and respond as appropriate.
Thread-Safe Collection Classes
The new System.Collections.Concurrent namespace introduces several new thread-safe collection classes that provide lock-free access to items whenever useful, and fine-grained locking when locks are appropriate. The use of these classes in multi-threaded scenarios should improve performance over collection types such as ArrayList, and List<(Of <(T>)>).
New synchronization primitives in the System.Threading namespace enable fine-grained concurrency and faster performance by avoiding expensive locking mechanisms. TheBarrier class enables multiple threads to work on an algorithm cooperatively by providing a point at which each task can signal its arrival and then block until the other participants in the barrier have arrived. The CountdownEvent class simplifies fork and join scenarios by providing an easy rendezvous mechanism. The ManualResetEventSlim class is a lock-free synchronization primitive similar to the ManualResetEvent class. ManualResetEventSlimis lighter weight but can only be used for intra-process communication. TheSemaphoreSlim class is a lightweight synchronization primitive that limits the number of threads that can access a resource or a pool of resources at the same time; it can be used only for intra-process communication. The SpinLock class is a mutual exclusion lock primitive that causes the thread that is trying to acquire the lock to wait in a loop, or spin, until the lock becomes available. The SpinWait class is a small, lightweight type that will spin for a time and eventually put the thread into a wait state if the spin count is exceeded.
Enhancements have been made that affect how integrated Windows authentication is handled by the HttpWebRequest, HttpListener, SmtpClient, SslStream, NegotiateStream, and related classes in the System.Net and related namespaces. Support was added for extended protection to enhance security. The changes to support extended protection are available only for applications on Windows 7. The extended protection features are not available on earlier versions of Windows. For more information, seeIntegrated Windows Authentication with Extended Protection.
The following sections describe new features in ASP.NET core services, Web Forms, Dynamic Data, and Visual Web Developer.
ASP.NET Core Services
ASP.NET introduces several features that improve core ASP.NET services, Web Forms, Dynamic Data, and Visual Web Developer. For more information, see What’s New in ASP.NET and Web Development.
ASP.NET Web Forms
Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0. Many enhancements have been made in this area for ASP.NET 4, including the following:
- The ability to set meta tags.
- More control over view state.
- Easier ways to work with browser capabilities.
- Support for using ASP.NET routing with Web Forms.
- More control over generated IDs.
- The ability to persist selected rows in data controls.
- More control over rendered HTML in the FormView and ListView controls.
- Filtering support for data source controls.
For ASP.NET 4, Dynamic Data has been enhanced to give developers even more power for quickly building data-driven Web sites. This includes the following:
- Automatic validation that is based on constraints defined in the data model.
- The ability to easily change the markup that is generated for fields in the GridView and DetailsView controls by using field templates that are part of your Dynamic Data project.
Visual Web Developer Enhancements
The Web page designer in Visual Studio 2010 has been enhanced for better CSS compatibility, includes additional support for HTML and ASP.NET markup code examples, and features a redesigned version of IntelliSense for JScript. In addition, two new deployment features called Web packaging and One-Click Publish make deploying Web applications easier.
The following sections describe new features in Windows Presentation Foundation (WPF) and Managed Extensibility Framework (MEF).
Windows Presentation Foundation
In the .NET Framework 4.0, Windows Presentation Foundation (WPF) contains changes and improvements in many areas. This includes controls, graphics, and XAML.
For more information, see What’s New in Windows Presentation Foundation Version 4.
Managed Extensibility Framework
The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4.0 that enables you to build extensible and composable applications. MEF enables application developers to specify points where an application can be extended, expose services to offer to other extensible applications, and create parts for consumption by extensible applications. It also enables easy discoverability of available parts based on metadata, without the need to load the assemblies for the parts.
For more information, see Managed Extensibility Framework. For a list of the MEF types, see the System.ComponentModel.Composition namespace.
For more information, see What’s New in ADO.NET.
Expression trees are extended with new types that represent control flow, for example,LoopExpression and TryExpression. These new types are used by the dynamic language runtime (DLR) and not used by LINQ.
Windows Communication Foundation (WCF) provides the new features and enhancements described in the following sections.
Support for WS-Discovery
The Service Discovery feature enables client applications to dynamically discover service addresses at run time in an interoperable way using WS-Discovery. The WS-Discovery specification outlines the message-exchange patterns (MEPs) required for performing lightweight discovery of services, both by multicast (ad hoc) and unicast (using a network resource).
Standard endpoints are pre-defined endpoints that have one or more of their properties (address, binding, contract) fixed. For example, all metadata exchange endpoints specifyIMetadataExchange as their contract, so there is no need for a developer to have to specify the contract. Therefore, the standard MEX endpoint has a fixedIMetadataExchange contract.
With the introduction of a set of messaging activities, it is easier than ever to implement workflows that send and receive data. These messaging activities enable you to model complex message exchange patterns that go outside the traditional send/receive or RPC-style method invocation.
Windows Workflow Foundation (WF) in .NET Framework 4.0 changes several development paradigms from earlier versions. Workflows are now easier to create, execute, and maintain.
Workflow Activity Model
The activity is now the base unit of creating a workflow, instead of using theSequentialWorkflowActivity or StateMachineWorkflowActivity classes. TheWorkflowElement class provides the base abstraction of workflow behavior. Activity authors implement WorkflowElement objects imperatively when they have to use the breadth of the runtime. The Activity class is a data-driven WorkflowElement object where activity authors express new behaviors declaratively in terms of other activity objects.
Richer Composite Activity Options
The Flowchart class is a powerful new control flow activity that enables authors to construct process flows more naturally. Procedural workflows benefit from new flow-control activities that model traditional flow-control structures, such as TryCatch and Switch.
Expanded Built-in Activity Library
New features of the activity library include the following:
- Data access activities for interacting with ODBC data sources.
- New flow control activities such as DoWhile, ForEach, and ParallelForEach.
- Activities for interacting with PowerShell and SharePoint.
Enhanced Persistence and Unloading
Workflow state data can be explicitly persisted by using the Persist activity. A host can persist a WorkflowInstance without unloading it. A workflow can specify no-persist zones when working with data that cannot be persisted so that persistence is postponed until the no-persist zone exits.
Improved Ability to Extend WF Designer Experience
The new WF Designer is built on Windows Presentation Foundation (WPF) and provides an easier model to use when rehosting the WF Designer outside Visual Studio. It also provides easier mechanisms for creating custom activity designers. For more information, see Extending the Workflow Designer.