Managed Code and Data

So what is managed code, then? Managed code is code that provides enough information to allow the common language runtime to perform the following tasks:

■ Given an address inside the code, locate the metadata describing the method

■ Handle exceptions

■ Store and retrieve security information

For the runtime to carry out these tasks, the code must pass a verification process— unless a network administrator has established a policy that allows code to run without verification. During the verification process, the JIT compiler examines the MSIL code and the metadata to determine whether the code can be classified as type-safe. Typesafe code is code that can be determined to access only memory locations that it owns. This restriction ensures that the code works and plays well with other programs and that the code is safe from causing accidental or malicious corruption. Without type safety, there's no way to reliably enforce security restrictions.

Related to managed code is managed data. Managed data is data that is allocated and freed automatically through the runtime using a process called garbage collection. With garbage collection, whenever an allocated item goes out of scope, the runtime cleans it up.

One consequence of using garbage collection is that the time and potentially even the order of destruction of objects can't be determined. For instance, consider the following C# code snippet. (I'll introduce C# in Chapter ; but even without knowing anything about C#, you should be able to understand this simple example.)

class MainApp {

public static void Main() {

System.String Hello = "Hello"; System.String World = "World!"; System.Console.WriteLine(Hello); System.Console.WriteLine(World);

Here two String objects are created, one containing the literal "Hello" and the other containing the literal "World!". Although the literals are declared in that order, there's no assurance that they will be destroyed in any particular order. Furthermore, there's no assurance that they will be destroyed as the strings go out of scope. The order, or timing, in the preceding example is meaningless, but it might make a difference in other examples.

The nondeterministic freeing of objects isn't a problem unless the object holds some persistent resources that the runtime doesn't manage—for instance, a database connection or a window handle. When an object holds such resources, the solution is to provide a Dispose method and implement the Disposable interface, which can be explicitly called to free resources. You'll see examples of this technique in subsequent chapters.

0 0

Post a comment