# Unit - III ( English - Version )

## **Assemblies in C#**

An **assembly** in C# is a compiled code library used for deployment, versioning, and security. An assembly can contain one or more **types** (classes, interfaces, structures, etc.) and is the fundamental unit of deployment in the .NET framework.

### **Types of Assemblies:**

1. **Private Assemblies:**
   * These are used by a single application.
   * They are stored in the application's directory or a subdirectory.
2. **Shared Assemblies:**
   * These are used by multiple applications.
   * Stored in the **Global Assembly Cache (GAC)**.
3. **Dynamic Assemblies:**
   * Created at runtime, typically using the `System.Reflection.Emit` namespace.
   * They can be loaded into an AppDomain without needing to be pre-compiled.

### **Global Assembly Cache (GAC):**

The **GAC** is a central repository for assemblies that are shared by multiple applications. Assemblies are stored in the GAC based on their **strong name**, which includes the assembly’s name, version, culture, and public key.

**How to Install Assemblies in GAC:**

* Use the `gacutil` tool or drag and drop assemblies into the GAC folder (`C:\Windows\Assembly`).

***

## **Threads in C#**

A **thread** is the smallest unit of execution in a process. In .NET, threads are part of the **System.Threading** namespace.

### **Creating and Managing Threads:**

1. **Thread Creation:**

   * You can create threads using the `Thread` class and start them with `Thread.Start()`.

   ```csharp
   Thread myThread = new Thread(new ThreadStart(MyMethod));
   myThread.Start();
   ```
2. **Thread State:**
   * Threads go through various states: **Unstarted**, **Running**, **WaitSleepJoin**, **Stopped**, etc.
3. **Thread Lifecycle:**
   * Once started, a thread executes the method it was passed, then terminates.

### **Thread Pooling:**

The **Thread Pool** manages a collection of worker threads. Instead of creating a new thread each time, you can use threads from the pool.

* **Advantages:** Reduces the overhead of creating and destroying threads.
* Use `ThreadPool.QueueUserWorkItem()` to queue a task.

  ```csharp
  ThreadPool.QueueUserWorkItem(WorkerMethod);
  ```

***

## **Thread Contexts and Concurrency**

### **Contexts:**

A **Thread Context** represents an environment for executing a thread, such as its execution stack, CPU state, and registers.

### **Concurrency:**

Concurrency refers to multiple threads making progress within overlapping time periods. **Thread synchronization** is required to ensure data consistency and prevent issues like race conditions.

### **Synchronization:**

Synchronization is necessary when multiple threads access shared resources to prevent data corruption or inconsistent results. C# provides various synchronization mechanisms:

1. **Locks (Monitor):**

   * `lock` is a C# keyword that simplifies using the **Monitor** class.
   * It ensures that only one thread can enter the critical section of code.

   ```csharp
   lock(myLockObject)
   {
       // Critical section
   }
   ```
2. **Monitor:**

   * Provides **Enter** and **Exit** methods to acquire and release a lock.

   ```csharp
   Monitor.Enter(myLockObject);
   try
   {
       // Critical section
   }
   finally
   {
       Monitor.Exit(myLockObject);
   }
   ```
3. **Reader-Writer Lock:**

   * A **ReaderWriterLock** allows multiple threads to read the shared resource but only one thread to write to it.

   ```csharp
   ReaderWriterLock rwLock = new ReaderWriterLock();
   rwLock.AcquireReaderLock(Timeout.Infinite);
   rwLock.ReleaseReaderLock();
   ```
4. **Mutex:**

   * A **Mutex** is a system-wide synchronization object. It can be used to synchronize threads across different processes.

   ```csharp
   Mutex mutex = new Mutex();
   mutex.WaitOne(); // Acquire
   mutex.ReleaseMutex(); // Release
   ```

***

## **AppDomains**

An **AppDomain** is a mechanism for isolating applications in the .NET runtime. Each application runs in its own AppDomain, which provides a boundary for execution, security, and configuration.

### **Why Use AppDomains?**

1. **Isolation:** AppDomains prevent one application from affecting another (e.g., memory corruption).
2. **Security:** AppDomains provide a boundary for security policies.
3. **Loading and Unloading Assemblies:** Assemblies can be loaded or unloaded dynamically in an AppDomain.

### **Creating and Managing AppDomains:**

* You can create and unload an AppDomain using `AppDomain.CreateDomain()` and `AppDomain.Unload()` methods.

  ```csharp
  AppDomain newDomain = AppDomain.CreateDomain("NewDomain");
  AppDomain.Unload(newDomain);
  ```

***

## **Processes in C#**

A **process** is an instance of a running application. A process can have one or more threads.

### **Process Class:**

The `System.Diagnostics.Process` class in C# is used to interact with processes.

* **Starting a Process:**

  ```csharp
  Process.Start("notepad.exe");
  ```
* **Getting Process Information:**

  ```csharp
  Process proc = Process.GetProcessesByName("notepad")[0];
  Console.WriteLine(proc.MainWindowTitle);
  ```

***

## **Concurrency and Synchronization**

Concurrency is a key concern when multiple threads are running simultaneously and accessing shared resources. You must ensure that operations are thread-safe to avoid issues such as race conditions or deadlocks.

### **Common Synchronization Mechanisms:**

1. **Locks:**
   * Locks help prevent data corruption by ensuring that only one thread at a time can access a resource.
2. **Monitors:**
   * Monitors allow threads to enter and exit critical sections in a controlled manner. `lock` is a syntactic sugar for the Monitor class.
3. **ReaderWriterLock:**
   * Allows multiple threads to read simultaneously, but exclusive access is required for writing.
4. **Mutex:**
   * Used to synchronize threads across different processes.
5. **Semaphore:**
   * A **Semaphore** is used to control access to a resource by limiting the number of threads that can use the resource concurrently.

***

## **Summary**

This unit focuses on the key aspects of managing threads, app domains, and assemblies in C#. It provides an understanding of how to deal with concurrency, synchronization, and processes in .NET applications. The key synchronization tools include locks, monitors, reader-writer locks, mutexes, and semaphores. AppDomains provide isolation and security for applications. Threads are managed through the `Thread` class, and thread pooling optimizes performance by reusing threads.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://v3noms-organization.gitbook.io/v3noms-byte/.net-framework-notes/.net-framework-syllabus/unit-iii-english-version.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
