06.1 .net memory management

21
C# Advanced Part 2

Upload: victor-matyushevskyy

Post on 25-May-2015

1.183 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: 06.1 .Net memory management

C# AdvancedPart 2

Page 2: 06.1 .Net memory management

Applications

• Console Windows apps• Windows Forms• Web services, WCF services• Web forms• ASP.NET MVC apps• Windows services• Libraries

Page 3: 06.1 .Net memory management

Assembly

• Is a deployment unit• .EXE or .DLL• Contains manifest + code

(metadata tables + IL)

Page 4: 06.1 .Net memory management

Types

Can contain:• Constant • Field• Instance constructor• Type constructor• Method. Method is not virtual by

default. Virtual, new , override, sealed, abstract

Page 5: 06.1 .Net memory management

Types (cont’d)

• Property. Can be virtual• Overloaded operator• Conversion operator• Event. Can be virtual• Type

Page 6: 06.1 .Net memory management

Access modifiers

• Private• Protected (Family)• Internal • Family and assembly -- Not

supported in C#• Family or assembly (protected

internal)• Public

Page 7: 06.1 .Net memory management

Types

• Value types – stack, inline• Reference types – heap, by reference

Page 8: 06.1 .Net memory management

Object lifetime

• Allocate memory. Fill it with 0x00.• Init memory -- constructor.• Use the object -- call methods,

access fields.• Cleanup.• Deallocate memory (only GC is

responsible for this).

Page 9: 06.1 .Net memory management

Object References

• CLR knows about all references to objects.

• Root reference (in active local var or in static field).

• Non-root reference (in instance field)

Page 10: 06.1 .Net memory management

Finalization

• Mechanism that allows the object to correctly cleanup itself before GC releases memory.

• Time when finalizers are called is undetermined.

• Order in which finalizers are called is undetermined.

• Partially constructed objects are also finalized

Page 11: 06.1 .Net memory management

IDisposable

• Used when the object needs explicit cleanup

Page 12: 06.1 .Net memory management

What are Exceptions?

• An exception is any error condition or unexpected behavior encountered by an executing program.

• In the .NET Framework, an exception is an object that inherits from the Exception Class class.

• The exception is passed up the stack until the application handles it or the program terminates.

Page 13: 06.1 .Net memory management

Use Exceptions or not use exceptions?

-• Вони невидимі з викликаючого коду.• Створюються непередбачувані точки виходу з метода.• Exceptions повільні. (exceptions use resources only when an exception occurs.)+ • Зручність використання.• Інформативність отриманих помилок більша по

відношенні до статус-кодів.• Принцип використання. Throw на самий верхній рівень.• Більш елегантні архітектурні рішення та зменшення

часу розробки.

Page 14: 06.1 .Net memory management

C# Exception handling• try…catch…finally• throw• Catch as high as you can• try{ }

catch(Exception1){ /*exception1 handler*/ }catch(Exception2) { /*exception2 handler*/ }catch(Exception) { /*exception handler*/ }

Page 15: 06.1 .Net memory management

IDisposable

• The primary use of this interface is to release unmanaged resources.

• When calling a class that implements the IDisposable interface, use the try/finally pattern to make sure that unmanaged resources are disposed of even if an exception interrupts your application.

Page 16: 06.1 .Net memory management

Working with streams

var fileStream = new FileStream(@"Path\To\file", FileMode.Open, FileAccess.Read);             try            {    

//Note: read from file stream here             }             finally            {                                fileStream.Dispose();             }             //Note: you can use file stream here, but this is bad idea

using (var fileStream = new FileStream(@"Path\To\file", FileMode.Open, FileAccess.Read))   {                 

//Note: read from file stream here             }             //Note: fileStream is not accessible here

Page 17: 06.1 .Net memory management

Attributes

• Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth).

Page 18: 06.1 .Net memory management

Aspect Oriented Programming

• Logging• Data validating• Security mechanism• …

Page 19: 06.1 .Net memory management

Validation sample (AOP sample)

http://msdn.microsoft.com/en-us/library/ff648831.aspx - Enterprise Library Validation Application Block

 public class User{

[StringLengthValidator(1, 255, MessageTemplate = "Login cannot be empty.")]         public string Login { get; set; }         [StringLengthValidator(1, 127, MessageTemplate = "Domain cannot be empty.")]

        public string Domain { get; set; }        

 public string FirstName { get; set; }          

public string LastName { get; set; }        

 [StringLengthValidator(1, 50, MessageTemplate = "Email cannot be empty.")]         public string Email { get; set; }

}

Page 20: 06.1 .Net memory management

Custom attributes

- Creating [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class LoggingRequiredAttribute : Attribute { }

- Usages public class UserService { [LoggingRequired] public static void CreateUser() { //Note: logic here }

public static void EditUser() { //Note: logic here } }

Page 21: 06.1 .Net memory management

Questions?