Skip to content

CLR (Common Language Runtime)

Genel Bakış

CLR, .NET uygulamalarının çalışma zamanı ortamıdır. Bu bölümde CLR'ın temel bileşenlerini, çalışma prensiplerini ve önemli özelliklerini inceleyeceğiz.

Mülakat Soruları ve Cevapları

1. CLR nedir ve temel görevleri nelerdir?

Cevap: CLR (Common Language Runtime), .NET uygulamalarının çalışma zamanı ortamıdır. Temel görevleri: - Memory management (Bellek yönetimi) - Type safety (Tip güvenliği) - Exception handling (Hata yönetimi) - Security (Güvenlik) - Thread management (İş parçacığı yönetimi) - Code execution (Kod çalıştırma)

Örnek Kod:

public class CLRExample
{
    // Memory management örneği
    public void MemoryExample()
    {
        // CLR heap'te yer ayırır
        var list = new List<int>();

        // CLR garbage collection yapar
        list = null;
    }

    // Type safety örneği
    public void TypeSafetyExample()
    {
        object obj = "string";
        // CLR runtime'da tip kontrolü yapar
        int number = (int)obj; // InvalidCastException
    }
}

2. CLR'ın bileşenleri nelerdir ve nasıl çalışır?

Cevap: 1. Class Loader: - Assembly'leri yükler - Metadata'yı okur - Tip bilgilerini oluşturur

  1. JIT Compiler:
  2. IL kodunu native koda dönüştürür
  3. Optimizasyonlar yapar
  4. Code caching kullanır

  5. Garbage Collector:

  6. Memory yönetimi yapar
  7. Generations kullanır (0, 1, 2)
  8. Finalization queue yönetir

  9. Security Engine:

  10. Code access security
  11. Role-based security
  12. Permission checking

Örnek Kod:

public class CLRComponents
{
    // JIT Compilation örneği
    public void JITExample()
    {
        // İlk çalıştırmada JIT compilation
        var result = Calculate(5, 10);

        // Sonraki çalıştırmalarda cached native code
        result = Calculate(5, 10);
    }

    private int Calculate(int a, int b)
    {
        return a + b;
    }

    // Garbage Collection örneği
    public void GCExample()
    {
        // Generation 0'da nesne oluşturulur
        var obj = new LargeObject();

        // Nesne kullanılmaz hale gelir
        obj = null;

        // Garbage Collection tetiklenir
        GC.Collect();
    }
}

3. CLR'da memory management nasıl çalışır?

Cevap: 1. Heap Yapısı: - Small Object Heap (SOH) - Large Object Heap (LOH) - Generations (0, 1, 2)

  1. Allocation:
  2. Stack allocation (value types)
  3. Heap allocation (reference types)
  4. Pinned objects

  5. Collection:

  6. Mark and sweep algoritması
  7. Compaction
  8. Finalization

Örnek Kod:

public class MemoryManagement
{
    // Stack allocation
    public void StackExample()
    {
        int number = 42; // Stack'te
        Point point = new Point(1, 2); // Stack'te (struct)
    }

    // Heap allocation
    public void HeapExample()
    {
        var list = new List<int>(); // Heap'te
        var obj = new object(); // Heap'te
    }

    // Pinned objects
    public unsafe void PinnedExample()
    {
        byte[] buffer = new byte[1000];
        fixed (byte* ptr = buffer)
        {
            // Pointer işlemleri
        }
    }
}

4. CLR'da exception handling nasıl çalışır?

Cevap: 1. Exception Types: - System.Exception - Custom exceptions - Checked/unchecked exceptions

  1. Exception Flow:
  2. Try-catch-finally blokları
  3. Exception propagation
  4. Stack unwinding

  5. Best Practices:

  6. Specific exception handling
  7. Exception logging
  8. Resource cleanup

Örnek Kod:

public class ExceptionHandling
{
    public void HandleException()
    {
        try
        {
            // Riskli kod
            ProcessData();
        }
        catch (FileNotFoundException ex)
        {
            // Spesifik hata yönetimi
            LogError(ex);
            HandleFileNotFound();
        }
        catch (Exception ex)
        {
            // Genel hata yönetimi
            LogError(ex);
            throw;
        }
        finally
        {
            // Kaynak temizleme
            CleanupResources();
        }
    }

    private void LogError(Exception ex)
    {
        // Hata loglama
    }
}

5. CLR'da thread management nasıl çalışır?

Cevap: 1. Thread Pool: - Worker threads - I/O completion threads - Thread scheduling

  1. Synchronization:
  2. Lock
  3. Monitor
  4. Semaphore
  5. Mutex

  6. Async/Await:

  7. Task-based asynchrony
  8. State machine
  9. Context switching

Örnek Kod:

public class ThreadManagement
{
    // Thread Pool kullanımı
    public void ThreadPoolExample()
    {
        ThreadPool.QueueUserWorkItem(state =>
        {
            // Arka plan işi
            ProcessData();
        });
    }

    // Async/Await kullanımı
    public async Task AsyncExample()
    {
        await ProcessDataAsync();
        // Context switch
        await ProcessMoreDataAsync();
    }

    // Synchronization
    private readonly object _lock = new object();
    public void SynchronizedMethod()
    {
        lock (_lock)
        {
            // Thread-safe kod
            UpdateSharedResource();
        }
    }
}

Best Practices

  1. Memory Management
  2. IDisposable pattern kullanımı
  3. using statement
  4. Large object heap yönetimi
  5. Finalization'dan kaçınma

  6. Exception Handling

  7. Specific exception handling
  8. Exception logging
  9. Resource cleanup
  10. Exception propagation

  11. Thread Safety

  12. Immutable objects
  13. Thread synchronization
  14. Async/await pattern
  15. Concurrent collections

Kaynaklar