Processes vs Threads وحياة كل منهم
الـ Process هو برنامج شغّال: ليه address space مستقل (ذاكرة خاصة)، وملفات مفتوحة، وهوية (PID). الـ Thread هو «خط تنفيذ» جوه الـ process. كل threads الـ process الواحدة بتشارك نفس الذاكرة (heap) بس كل thread ليه stack خاص ومسجلات (registers) خاصة.
| Process | Thread | |
|---|---|---|
| الذاكرة | خاصة ومعزولة (حماية من الـ OS) | مشتركة (heap) + stack خاص |
| تكلفة الإنشاء | غالية (ملايين الـ cycles، mapping للذاكرة) | أرخص بكتير (لكن مش مجانية: stack ~1MB) |
| التواصل | IPC: pipes, sockets, shared memory, files | متغيرات مشتركة (محتاجة synchronization) |
| لو حصل crash | الـ process وحدها بتقع | exception غير معالج في thread بيقع الـ process كلها |
| مثال | تطبيقك + SQL Server + nginx = 3 processes | كل request في Kestrel بيتنفذ على thread من الـ pool |
دورة حياة الـ Thread
using System.Diagnostics;
// ---- THREADS: share the same variable ----
int shared = 0;
var t1 = new Thread(() => shared = 42);
t1.Start();
t1.Join(); // wait until the thread terminates
Console.WriteLine(shared); // 42 -> the thread wrote into OUR memory
Console.WriteLine($"Current PID={Environment.ProcessId}, managed thread id={Environment.CurrentManagedThreadId}");
// ---- PROCESSES: separate memory, communicate via streams ----
var psi = new ProcessStartInfo("dotnet", "--version")
{
RedirectStandardOutput = true,
UseShellExecute = false
};
using var child = Process.Start(psi)!; // creates a NEW process with its own address space
string output = await child.StandardOutput.ReadToEndAsync();
await child.WaitForExitAsync();
Console.WriteLine($"child PID={child.Id} exit={child.ExitCode} output={output.Trim()}");الشرح والتتبع
new Thread(...)بيخلق thread جديد في نفس الـ process، وبيكتب مباشرة في المتغيرshared(لأنه captured في heap).Joinبيخلي الـ main thread يستنى (حالة Waiting) لحد ما الـ thread يخلص ويدخل Terminated.Process.Startبيطلب من الـ OS يعمل process جديدة (fork/execعلى Linux،CreateProcessعلى Windows) ليها PID مختلف وذاكرة منفصلة. مفيش طريقة نكتب بها في متغيراتها، فالتواصل بس عن طريق stdout/stdin.- في الـ backend: IIS/Kestrel بيشغّلوا الـ API في process، والـ threads جواها بتخدم الـ requests. والـ microservices كل واحدة process (غالباً container) منفصلة، وده بيدّي عزل للأعطال مقابل تكلفة التواصل الشبكي.
Scheduling و Context Switching
عدد الـ threads أكبر بكتير من عدد الـ CPU cores. الـ Scheduler في الـ kernel هو اللي بيقرر مين يشتغل على أي core ولأد إيه. كل thread بياخد time slice (عادةً ملّي ثانية أو أقل)، وبعدين بيتعمله preempt (يتقاطع) ويدخل thread تاني. الـ OS بيستخدم preemptive multitasking: مش لازم الكود يتنازل بإرادته.
إيه اللي بيتحكم في الاختيار؟
- الأولوية (priority) للـ thread/process.
- Fairness: الكل ياخد نصيب (Linux CFS بيعتمد على «الوقت الافتراضي المستهلك»).
- I/O-bound threads بتاخد أفضلية لأنها بتقعد تستنى كتير.
- CPU affinity (تثبيت على cores).
Context Switch
الـ kernel بيحفظ حالة الـ thread الحالي (registers، program counter، stack pointer) وبيحمّل حالة thread تاني. التكلفة المباشرة: ميكرو ثواني. التكلفة غير المباشرة الأكبر: الـ CPU cache و TLB بيبقوا «بارد» للـ thread الجديد ⇒ cache misses.
using System.Diagnostics;
// CPU-bound work: count primes in a range
static int CountPrimes(int from, int to)
{
int count = 0;
for (int n = Math.Max(2, from); n < to; n++)
{
bool prime = true;
for (int d = 2; (long)d * d <= n; d++)
if (n % d == 0) { prime = false; break; }
if (prime) count++;
}
return count;
}
const int Max = 2_000_000;
Console.WriteLine($"Cores: {Environment.ProcessorCount}");
foreach (int workers in new[] { 1, Environment.ProcessorCount, Environment.ProcessorCount * 16 })
{
var sw = Stopwatch.StartNew();
int chunk = Max / workers;
var tasks = Enumerable.Range(0, workers)
.Select(i => Task.Factory.StartNew(
() => CountPrimes(i * chunk, i == workers - 1 ? Max : (i + 1) * chunk),
TaskCreationOptions.LongRunning)) // LongRunning = dedicated thread, not pool
.ToArray();
int total = (await Task.WhenAll(tasks)).Sum();
Console.WriteLine($"{workers,4} threads -> {sw.ElapsedMilliseconds,5} ms (primes={total})");
}
// Typical shape on an 8-core machine:
// 1 threads -> 900 ms
// 8 threads -> 150 ms <- near-linear speedup up to the number of cores
// 128 threads -> 160 ms <- no gain; extra threads only add switching + memory- الشغل CPU-bound: كل thread محتاج core بالكامل. الـ speedup بيقف عند
عدد الـ cores. TaskCreationOptions.LongRunningبيخلي الـ Task يشتغل على thread مخصص مش من الـ thread pool عشان ما يخنقش الـ pool.- الأرقام تقريبية وبتختلف بحسب الجهاز، لكن الشكل ثابت: تحسّن لحد عدد الـ cores، وبعدها لا تحسن (وأحياناً تراجع) بسبب الـ context switching وزيادة استهلاك الذاكرة (كل thread له stack).
- الدرس العملي: للشغل الـ CPU-bound استخدم عدد threads ≈ cores (
Parallel.Forبيعمل ده). للـ I/O-bound مش محتاج threads كتير أصلاً — محتاج async (قسم Thread Pools).
User Mode vs Kernel Mode و System Calls
المعالج بيشتغل في مستويين امتيازات. User mode (ring 3): كودك أنت و .NET runtime، ومفيش وصول مباشر للهاردوير أو لذاكرة process تانية. Kernel mode (ring 0): نواة الـ OS، وليها كل الصلاحيات. ده بيحمي النظام: تطبيق بايظ ميقدرش يقفل الجهاز.
لو كودك عايز يعمل أي حاجة تخص مورد مشترك (يقرا ملف، يفتح socket، يطلب ذاكرة، يعمل thread)، بيعمل System Call: طلب للـ kernel عن طريق instruction خاصة. المعالج بيبدّل لـ kernel mode، الـ kernel ينفذ ويرجع النتيجة، وبعدين يرجع لـ user mode.
# Run a tiny program under strace and filter file-related syscalls
strace -f -e trace=openat,read,write,close -o trace.txt dotnet run --no-build
grep -E 'openat.*data.txt|read\(' trace.txt | head
# Typical lines:
# openat(AT_FDCWD, "/app/data.txt", O_RDONLY|O_CLOEXEC) = 12 <- File.OpenRead
# read(12, "hello world\n", 4096) = 12 <- stream.Read
# close(12) = 0 <- Dispose()using System.Diagnostics;
// Many tiny writes = many syscalls (unbuffered)
var sw = Stopwatch.StartNew();
using (var fs = new FileStream("tiny.bin", FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 1)) // 1 = effectively no buffering
{
for (int i = 0; i < 200_000; i++) fs.WriteByte(1); // ~200k write() syscalls
}
Console.WriteLine($"unbuffered: {sw.ElapsedMilliseconds} ms");
// Same data, one buffer = a handful of syscalls
sw.Restart();
File.WriteAllBytes("big.bin", new byte[200_000]); // one write
Console.WriteLine($"single write: {sw.ElapsedMilliseconds} ms");- كل
WriteByteبدون buffering = syscall = انتقال user→kernel→user. الأرقام بتبقى أسوأ بكتير من نسخة الـ buffer الواحد (غالباً أضعاف عديدة). - عشان كده الـ
FileStreamوالـStreamWriterبيستخدموا buffers (4KB افتراضياً) وBufferedStream، وعشان كده الـ batching مبدأ مهم: إكتب شوية كبيرة بدل ألف صغيرة (ينطبق على DB queries والـ network كمان). strace(أوdotnet-trace/perf) بيوريك الـ syscalls الفعلية وبيفسر ظواهر زي «ليه الـ app بتفتح ملف 10 آلاف مرة؟».
أي عملية I/O (network، disk، DB connection) تعدي على syscall. وده سبب إن الـ context switch و buffering و batching مهمين في الأداء. وإن الـ container مش VM: الـ containers بتتشارك نفس الـ kernel مع الـ host، فالـ syscalls بتروح لنفس الـ kernel (وده بيفسر ليه seccomp profiles بتقيّدها لأمان الـ container).
Stack و Heap و Virtual Memory
Stack vs Heap
Stack
- خاص بكل thread، بيشتغل LIFO.
- بيخزن: method call frames، المتغيرات المحلية، value types المحلية، عناوين الرجوع.
- الحجز والتحرير سريع جداً (تحريك pointer) ومن غير GC.
- حجمه محدود (عادةً ~1MB لكل thread في .NET على Windows، وأكبر على Linux). تجاوزه ⇒
StackOverflowException(process crash).
Heap
- مشترك بين كل threads الـ process.
- بيخزن: الـ objects (reference types)، arrays، strings.
- الحجز أغلى والتحرير بيتم عن طريق Garbage Collector (managed heap).
- الحجم محدود بالذاكرة المتاحة. تجاوزه ⇒
OutOfMemoryException.
struct PointS { public int X, Y; } // value type
class PointC { public int X, Y; } // reference type
static void Demo()
{
int n = 5; // stack
var ps = new PointS { X = 1, Y = 2 }; // stack (copied on assignment)
var pc = new PointC { X = 1, Y = 2 }; // heap object; `pc` (the reference) is on the stack
var copyS = ps; copyS.X = 99; // changes the COPY only
var copyC = pc; copyC.X = 99; // both names point to the same object
Console.WriteLine($"{ps.X} {pc.X}"); // 1 99
Span<int> buffer = stackalloc int[128]; // 512 bytes on the stack: no GC allocation
buffer[0] = n;
}
// Stack overflow: unbounded recursion
static int Boom(int n) => Boom(n + 1) + 1; // each call adds a frame -> eventually crashes the process (not catchable)- Value types (
int,struct) بيتنسخوا عند الـ assignment، فتعديل النسخة مبيأثرش على الأصل. Reference types بيتنسخ فيها المؤشر بس، فالاتنين بيشاوروا على نفس الـ object. - مقولة «value types دايماً على الـ stack» غير دقيقة: لو struct جوه class أو في array أو captured في lambda بيعيش جوه الـ heap مع الـ object اللي بيحويه.
stackallocمعSpan<T>بيحجز على الـ stack من غير تحميل على الـ GC، مفيد للـ buffers الصغيرة المؤقتة (استخدمه بحذر وبأحجام صغيرة).- الـ GC: كل allocation على الـ heap بيزيد ضغط الـ GC. الـ allocations الكتير في hot path بتعمل pauses. استخدم
Span/ArrayPool/structلما القياس يثبت إنها مشكلة.
Virtual Memory و Paging
كل process بتشوف عناوين «افتراضية» (virtual addresses) متصلة وخاصة بيها، ومش العناوين الفعلية في الـ RAM. الـ CPU (وحدة MMU) مع الـ OS بيترجموا العنوان الافتراضي لعنوان فعلي عن طريق page tables. الذاكرة متقسمة لـ pages (غالباً 4KB).
Segmentation fault/access violation.using System.Diagnostics;
using System.IO.MemoryMappedFiles;
// Memory-mapped file: the OS maps the file into virtual memory; pages load on demand (page faults)
File.WriteAllBytes("data.bin", new byte[100 * 1024 * 1024]); // 100 MB file
using var mmf = MemoryMappedFile.CreateFromFile("data.bin", FileMode.Open);
using var view = mmf.CreateViewAccessor(0, 4096); // map only the first page
view.Write(0, 123); // touches page 0 -> loaded + marked dirty
Console.WriteLine(view.ReadInt32(0)); // 123
var p = Process.GetCurrentProcess();
Console.WriteLine($"Working set: {p.WorkingSet64 / 1024 / 1024} MB"); // physical RAM currently used
Console.WriteLine($"Virtual: {p.VirtualMemorySize64 / 1024 / 1024} MB"); // address space reserved (can be much larger)
Console.WriteLine($"GC heap: {GC.GetTotalMemory(false) / 1024 / 1024} MB");- الـ memory-mapped file بيخلي الـ OS يحمّل الصفحات عند الحاجة فقط (demand paging)، فمقدرش تحمّل ملف 100MB كامل في الذاكرة بتكلفة قراءة بس اللي بتستخدمه.
- Working Set هو اللي في الـ RAM فعلاً دلوقتي. Virtual size هو الـ address space المحجوز وممكن يكون أكبر بكتير. الاتنين مختلفين عن حجم الـ GC heap.
- الـ container مع حد ذاكرة (مثلاً 512MB): لو الـ working set عدى الحد الـ kernel بيقتل الـ process (OOMKilled) بدل ما يعمل swap. الـ .NET GC بيقرا الـ cgroup limit ويحدد الـ heap hard limit بنسبة (غالباً 75% من الـ limit) لتجنب ده.
Concurrency vs Parallelism
Concurrency
التعامل مع أكتر من حاجة في نفس الفترة، حتى لو على core واحد (بالتبديل بينهم). مشكلة تنظيم. مثال: سيرفر بيخدم 10,000 request متزامنين بعدد threads قليل لأن أغلبهم بيستنوا I/O.
Parallelism
التنفيذ الفعلي لأكتر من حاجة في نفس اللحظة على cores متعددة. مشكلة سرعة للشغل الـ CPU-bound. مثال: معالجة صور على 8 cores.
// CPU-bound => parallelism: split the work across cores
double[] data = Enumerable.Range(1, 5_000_000).Select(i => (double)i).ToArray();
double sum = 0;
var gate = new Lock();
Parallel.ForEach(
System.Collections.Concurrent.Partitioner.Create(0, data.Length),
() => 0.0, // thread-local accumulator
(range, _, local) => { for (int i = range.Item1; i < range.Item2; i++) local += Math.Sqrt(data[i]); return local; },
local => { lock (gate) sum += local; }); // combine once per thread
Console.WriteLine(sum);
// I/O-bound => concurrency with async: no thread is blocked while waiting
using var http = new HttpClient();
string[] urls = ["https://example.com", "https://example.org", "https://example.net"];
var pages = await Task.WhenAll(urls.Select(u => http.GetStringAsync(u))); // 3 requests in flight, 0 threads blocked
Console.WriteLine(pages.Sum(p => p.Length));- الجزء الأول CPU-bound ⇒
Parallel.ForEachبيقسّم المدى على threads بعدد الـ cores. كل thread بيجمع في متغير محلي (local) ثم بنجمعهم تحتlockمرة واحدة لكل thread بدل lock لكل عنصر (ده بيتجنب الـ contention). - الجزء التاني I/O-bound ⇒
Task.WhenAllبيبدأ 3 requests وبيستنى كلهم من غير ما يحجز thread واحد أثناء الانتظار. - الخطأ الشائع: استخدام
Task.Run(() => http.GetString(...))للـ I/O (بيحجز thread من الـ pool طول فترة الانتظار)، أو استخدامasyncللـ CPU-bound وتوقع إنه هيسرّعه (async لا يخلق parallelism).
Race Conditions
الـ Race Condition هو إن نتيجة البرنامج بتعتمد على توقيت تنفيذ threads متزامنة على بيانات مشتركة. أصعب الـ bugs لأنها مش بتظهر دايماً، وغالباً تختفي لما تعمل debug أو log (heisenbug).
// ❌ BUG: counter++ is read-modify-write, not atomic
int unsafeCounter = 0;
Parallel.For(0, 1_000_000, _ => { unsafeCounter++; });
Console.WriteLine($"unsafe: {unsafeCounter:N0}"); // < 1,000,000 (varies every run)
// ✅ Fix 1: Interlocked — a single atomic CPU instruction (fastest for simple counters)
int atomicCounter = 0;
Parallel.For(0, 1_000_000, _ => { Interlocked.Increment(ref atomicCounter); });
Console.WriteLine($"interlocked: {atomicCounter:N0}"); // 1,000,000
// ✅ Fix 2: lock — protects a critical SECTION (needed when several variables change together)
int lockedCounter = 0;
var gate = new Lock(); // System.Threading.Lock (.NET 9+)
Parallel.For(0, 1_000_000, _ => { lock (gate) { lockedCounter++; } });
Console.WriteLine($"lock: {lockedCounter:N0}"); // 1,000,000
// ✅ Fix 3: avoid sharing — thread-local partial results, combine at the end
long total = 0;
Parallel.For(0, 1_000_000, () => 0L, (i, _, local) => local + 1, local => Interlocked.Add(ref total, local));
Console.WriteLine($"no sharing: {total:N0}"); // 1,000,000الشرح
unsafeCounter++بيتحول لـ 3 خطوات: (1) read (2) add (3) write. thread تاني ممكن يدخل بينهم فيكتب فوق التحديث.Interlocked.Incrementبتنفذ الـ 3 خطوات كـ atomic operation (CPUlock xadd). مناسب لـ counter واحد فقط.lockبيسمح لـ thread واحد في الوقت بدخول الـ critical section. بيشتغل لما التحديث يشمل أكتر من متغير (مثلاً رصيد + سجل العمليات).- الحل الأفضل غالباً هو عدم المشاركة: كل thread يحسب لنفسه وبعدين نجمع. (أقل contention وأسرع).
- الأنواع الأخرى: check-then-act (
if (!dict.ContainsKey(k)) dict[k] = v;على Dictionary مشترك) و lazy initialization غير آمنة. استخدمConcurrentDictionary.GetOrAddوLazy<T>.
الـ Singleton services مشتركة بين كل الـ requests = threads متعددة. أي mutable field فيها (مثل List<T> أو Dictionary عادي أو متغير counter) لازم يتحمى، وإلا هيحصل race conditions. فضّل الـ Singletons stateless أو immutable أو thread-safe.
Synchronization: Locks و Mutexes و Semaphores
الـ synchronization هي أدوات بتنسّق وصول الـ threads للبيانات المشتركة. كل أداة بتحل مشكلة مختلفة وبتكلّف أداء مختلف.
| الأداة | بتعمل إيه | النطاق | async-friendly؟ | استخدمها لـ |
|---|---|---|---|---|
lock / Monitor / Lock | Mutual exclusion: thread واحد في الـ critical section | داخل process | لا (متعملش await جواه) | حماية state قصير في الذاكرة |
Interlocked | عمليات atomic على متغير واحد | داخل process | نعم (مفيش blocking) | counters، flags، lock-free |
Mutex | Mutual exclusion على مستوى الـ OS | بين processes | لا | تأكد إن instance واحدة من التطبيق شغالة |
SemaphoreSlim | عدّاد: يسمح لـ N threads معاً | داخل process | نعم (WaitAsync) | throttling: max 5 نداءات متزامنة لخدمة |
ReaderWriterLockSlim | قراء كتير أو كاتب واحد | داخل process | لا | read-heavy shared data |
// ---- lock: protect an invariant that spans two fields ----
public sealed class BankAccount
{
private readonly Lock _lock = new(); // private dedicated lock object (.NET 9+). Before: private readonly object _lock = new();
private decimal _balance;
private readonly List<string> _log = [];
public void Deposit(decimal amount)
{
lock (_lock) // Monitor.Enter / Exit under the hood, released even on exceptions
{
_balance += amount;
_log.Add($"deposit {amount}"); // both updates happen atomically w.r.t. other lock users
}
}
public bool TryWithdraw(decimal amount)
{
lock (_lock)
{
if (_balance < amount) return false; // check-then-act is now safe
_balance -= amount;
_log.Add($"withdraw {amount}");
return true;
}
}
}
// ---- SemaphoreSlim: limit concurrency of ASYNC work (lock can't span an await) ----
public sealed class RateLimitedClient(HttpClient http)
{
private readonly SemaphoreSlim _gate = new(initialCount: 3); // max 3 concurrent requests
public async Task<string> GetAsync(string url, CancellationToken ct)
{
await _gate.WaitAsync(ct); // takes a slot or waits asynchronously (no thread blocked)
try { return await http.GetStringAsync(url, ct); }
finally { _gate.Release(); } // ALWAYS release in finally
}
}
// ---- Mutex (named): only ONE instance of the app per machine ----
using var mutex = new Mutex(initiallyOwned: true, name: "Global\\MyApp.SingleInstance", out bool createdNew);
if (!createdNew) { Console.WriteLine("Already running."); return; }
// ---- ReaderWriterLockSlim: many readers OR one writer ----
var rw = new ReaderWriterLockSlim();
rw.EnterReadLock(); try { /* read shared data */ } finally { rw.ExitReadLock(); }
rw.EnterWriteLock(); try { /* modify shared data */ } finally { rw.ExitWriteLock(); }شرح السطور المهمة
lock (_lock)بيضمن إن الـ block مش بيتنفذ إلا من thread واحد في نفس الوقت. بنستخدم lock object خاص (private) مشthisولاtypeof(X)ولا string، لأن كود برا ممكن يقفل على نفس الـ object ويعمل deadlock.- في
TryWithdrawفحص الرصيد والخصم جوه نفس الـ lock: لو مش كده thread تاني ممكن يسحب بينهم ⇒ رصيد سالب (race من نوع check-then-act). - الـ
lockمينفعش يحتوي await (الـ compiler بيمنعه)، لأن ممكن يكمل على thread تاني. للـ async استخدمSemaphoreSlim.WaitAsync. - الـ
try/finallyمعReleaseإجباري: لو حصل exception من غير release الـ slot بيضيع للأبد ⇒ الـ semaphore بيقفل تدريجياً. Mutexمسمّى بيشتغل بين processes (الـ OS هو اللي بيديره) وبالتالي أبطأ منlock. حرفGlobal\\في Windows بيخليه على مستوى الجهاز.- الـ
ReaderWriterLockSlimبيفيد لما القراءات أكتر بكتير من الكتابات وكل قراءة غالية نسبياً؛ للـ critical sections القصيرة الـlockالعادي غالباً أسرع وأبسط.
خلي الـ critical section أقصر ما يمكن: بلاش I/O أو network أو حاجة بطيئة جواها (كل threads التانية واقفة). وبلاش تنادي كود غير معروف (callbacks/events) وانت ماسك lock (هيتعمل deadlock بسهولة).
Deadlocks
الـ Deadlock هو إن threads (أو أكتر) كل واحد ماسك مورد ومنتظر مورد ماسكه التاني، فمحدش يكمل أبداً. مفيش exception ولا crash، الـ request بس بتفضل معلقة.
الـ deadlock بيحصل لما أربع شروط (Coffman) تتحقق مع بعض: (1) Mutual exclusion: المورد مش مشترك. (2) Hold and wait: ماسك مورد وبيطلب تاني. (3) No preemption: مينفعش تاخد المورد بالقوة. (4) Circular wait: دايرة انتظار. كسر أي واحد منهم بيمنع الـ deadlock.
var a = new object();
var b = new object();
// ❌ DEADLOCK: opposite lock order
var t1 = Task.Run(() => { lock (a) { Thread.Sleep(100); lock (b) { Console.WriteLine("t1 done"); } } });
var t2 = Task.Run(() => { lock (b) { Thread.Sleep(100); lock (a) { Console.WriteLine("t2 done"); } } });
try { await Task.WhenAll(t1, t2).WaitAsync(TimeSpan.FromSeconds(2)); }
catch (TimeoutException) { Console.WriteLine("Deadlock detected (timeout)"); }
// ✅ FIX 1: always acquire locks in the SAME global order (breaks circular wait)
var f1 = Task.Run(() => { lock (a) { lock (b) { Console.WriteLine("f1 done"); } } });
var f2 = Task.Run(() => { lock (a) { lock (b) { Console.WriteLine("f2 done"); } } });
await Task.WhenAll(f1, f2);
// ✅ FIX 2: try with a timeout and back off (breaks hold-and-wait)
static bool TryBoth(object x, object y, TimeSpan timeout)
{
if (!Monitor.TryEnter(x, timeout)) return false;
try
{
if (!Monitor.TryEnter(y, timeout)) return false;
try { /* critical work with both */ return true; }
finally { Monitor.Exit(y); }
}
finally { Monitor.Exit(x); }
}التتبع
a، t2 بياخد b (بعد Sleep الاتنين اتأكدوا إنهم أخدوا أول lock).b ⇒ مشغول ⇒ بيستنى. t2 بيحاول ياخد a ⇒ مشغول ⇒ بيستنى.WaitAsync(2s) بيرمي TimeoutException عشان نكتشف المشكلة (من غيره البرنامج هيتعلق).a أولاً، اللي ياخدها بيكمل والتاني يستنى في أول lock وهو ماسكش حاجة ⇒ مفيش دايرة.استدعاء .Result أو .Wait() أو .GetAwaiter().GetResult() على Task غير مكتمل بيحجز thread منتظر. في تطبيقات فيها SynchronizationContext (WinForms/WPF/ASP.NET القديم) ده بيعمل deadlock كلاسيكي لأن الـ continuation محتاجة نفس الـ thread المحجوز. ASP.NET Core ملوش SynchronizationContext فمفيش deadlock حقيقي هناك، لكن بيحصل Thread Pool Starvation (القسم الجاي). القاعدة: async all the way.
إزاي تكتشف deadlock في الـ production؟
- الـ request بتعلق من غير errors و CPU قليل ⇒ علامة.
- خد dump:
dotnet-dump collect -p <pid>ثمdotnet-dump analyzeوأمرclrstack -all(أوsyncblk) بيوريك كل thread مستني مين. - أو
dotnet-stack report -p <pid>للـ stacks بدون إيقاف العملية.
Thread Pools و Asynchronous I/O
إنشاء thread جديد غالي (ذاكرة stack + وقت)، فبدل ما نخلق ونقتل threads لكل شغلة، بنحتفظ بـ pool من threads جاهزة بتاخد شغل من queue. الـ ThreadPool في .NET هو اللي بيشغّل Task.Run و async continuations ومعالجة requests في Kestrel.
I/O: Blocking vs Asynchronous
Blocking I/O
الـ thread بينادي read() وبيتحجز (حالة Waiting) لحد ما الداتا توصل. لو 1000 request كل واحد بيستنى DB، محتاج 1000 thread محجوزة وبتاكل ذاكرة وبتعمل context switches.
Asynchronous I/O
الـ thread بيبدأ العملية ويتحرر فوراً. الـ OS بيراقب الإنجاز (IOCP على Windows، epoll على Linux) ولما تخلص بيشغّل الـ continuation على أي thread من الـ pool. مفيش thread مخصص أثناء الانتظار.
Thread Pool Starvation
الـ pool بيبدأ بعدد threads = عدد الـ cores (الحد الأدنى) وبيزوّد threads جديدة ببطء (حوالي واحد كل 500ms تقريباً) لما كل اللي عنده محجوز. لو threads كتير اتحجزت بـ blocking calls (.Result, Thread.Sleep, sync DB calls) والـ requests بتزيد، الـ queue بيطول ⇒ latency بتنفجر رغم إن الـ CPU قليل. ده thread pool starvation.
// ❌ Blocks a pool thread for 2 seconds per request. With 8 cores and 200 concurrent users, the pool starves.
app.MapGet("/bad", () =>
{
Thread.Sleep(2000); // simulates sync I/O (e.g. .Result on HttpClient)
return "done";
});
// ❌ Also blocks: "sync over async"
app.MapGet("/bad2", (IHttpClientFactory f) =>
f.CreateClient().GetStringAsync("https://slow.example.com").Result);
// ✅ Frees the thread while waiting
app.MapGet("/good", async () =>
{
await Task.Delay(2000); // simulates async I/O
return "done";
});
app.MapGet("/good2", async (IHttpClientFactory f, CancellationToken ct) =>
await f.CreateClient().GetStringAsync("https://slow.example.com", ct));
// Diagnostics: how loaded is the pool right now?
app.MapGet("/pool", () => new
{
threads = ThreadPool.ThreadCount,
queued = ThreadPool.PendingWorkItemCount,
completed = ThreadPool.CompletedWorkItemCount
});/badبيحجز thread 2 ثانية. مع 200 طلب متزامن محتاج 200 thread لكن الـ pool عنده ~8 وبيزيد ببطء ⇒ طوابير و latency بالثواني، رغم إن الـ CPU شبه فاضي./goodبيتحرر الـ thread أثناءawaitفنفس الـ 8 threads بتخدم آلاف الـ requests لأن أغلب وقتها انتظار.ThreadPool.PendingWorkItemCountمؤشر مبكر: لو كبير ومستمر فالـ pool مشبّع. أدوات:dotnet-counters monitorبيعرضthreadpool-queue-lengthوthreadpool-thread-count.- حل سريع مؤقت
ThreadPool.SetMinThreads(بيخلي الـ pool يزود بسرعة)، لكن ده تخفيف مش علاج. العلاج: شيل الـ blocking.
async/await مبيخلقش threads. هو state machine بيقسّم الـ method لأجزاء وبيشغّل الجزء التالي لما الـ I/O يخلص. وللـ CPU-bound محتاج threads فعلاً (Task.Run/Parallel) — لكن متستخدمش Task.Run داخل ASP.NET Core request لتجميل الـ blocking؛ ده بينقل المشكلة لـ thread تاني من نفس الـ pool.
File Systems و I/O
الـ file system بينظّم البيانات على الـ disk في ملفات ومجلدات. على Linux (ext4/xfs): الملف له inode (بيحتفظ بالـ metadata: الحجم، الصلاحيات، مكان الـ blocks) والاسم مجرد entry في directory بتشاور على الـ inode. الـ journaling بيحمي الـ consistency بعد crash. وpage cache بيخزن الملفات المقروءة في الـ RAM، فـ القراءة التانية أسرع بكتير. الكتابة بتروح للـ cache أولاً (write-back) وبعدين للـ disk؛ fsync هو اللي بيجبر الكتابة الفعلية على الـ disk.
// ❌ Loads the whole file into memory: a 2 GB log = 2 GB of RAM (and LOH allocations)
var all = await File.ReadAllLinesAsync("huge.log");
// ✅ Stream line by line: constant memory
await foreach (var line in ReadLinesAsync("huge.log"))
if (line.Contains("ERROR")) Console.WriteLine(line);
static async IAsyncEnumerable<string> ReadLinesAsync(string path)
{
// useAsync: true => real async I/O instead of blocking a thread
await using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 64 * 1024, useAsync: true);
using var reader = new StreamReader(fs);
while (await reader.ReadLineAsync() is { } line) yield return line;
}
// Durability: WriteAllText returns when data is in the OS cache, NOT necessarily on disk.
await using (var fs = new FileStream("important.dat", FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
{
await fs.WriteAsync("critical"u8.ToArray());
await fs.FlushAsync();
fs.Flush(flushToDisk: true); // fsync: survive a power loss
}- تحميل ملف كبير بالكامل بيستهلك ذاكرة بحجمه (وعلى الـ Large Object Heap لو أكبر من 85KB). الـ streaming بيحافظ على استهلاك ثابت.
useAsync: trueبيطلب async I/O حقيقي من الـ OS بدل ما يحجز thread.- الـ
Flush(true)(fsync) بيضمن إن الداتا فعلاً على الـ disk. بدونه ممكن تضيع في حالة انقطاع الكهرباء. غالي، فاستخدمه بس للداتا الحرجة (الـ databases بتعمل كده في الـ WAL).
Resource Management
الـ OS بيدّي كل process موارد محدودة: file descriptors/handles، sockets، ذاكرة، CPU، threads. تسريب أي مورد (مش بيتحرر) بيسبب أعطال بعد ساعات أو أيام من التشغيل: Too many open files، OutOfMemory، أو hang.
// ❌ Leak: if an exception happens before Close(), the file handle stays open until the GC finalizer (non-deterministic)
var fs = new FileStream("a.txt", FileMode.Open);
var data = new byte[fs.Length];
fs.Read(data);
fs.Close();
// ✅ using: Dispose() is called even if an exception is thrown
using (var stream = new FileStream("a.txt", FileMode.Open))
{
var buffer = new byte[stream.Length];
stream.Read(buffer);
} // handle released here
// C# 8+: using declaration — disposed at the end of the enclosing scope
using var conn = new Microsoft.Data.SqlClient.SqlConnection("...");
await using var tx = await conn.BeginTransactionAsync(); // IAsyncDisposable
// Your own resource: implement IDisposable correctly
public sealed class TempFile : IDisposable
{
public string Path { get; } = System.IO.Path.GetTempFileName();
public void Dispose() { if (File.Exists(Path)) File.Delete(Path); }
}- الـ GC بيدير الذاكرة بس، مش الـ handles والـ sockets والـ connections. دي unmanaged resources لازم تتحرر بـ
Dispose. - الـ
usingبيتحول لـtry/finallyبيستدعيDispose. الـ using declaration أنضف (من غير nesting). - حدود الـ OS: على Linux
ulimit -nبيحدد أقصى file descriptors لكل process (غالباً 1024 كـ soft default). الـ sockets كمان بتتحسب منها. تسريب connections ⇒Too many open files. - مؤشرات التسريب: استهلاك يزيد مع الوقت (
dotnet-counters)،lsof -p <pid> | wc -lبيعد الـ handles المفتوحة، وعدد threads بيكبر.
في Docker/Kubernetes بتحدد memory limit و CPU limit. تخطي الذاكرة = OOMKilled (الـ kernel بيقتل الـ process مباشرة بدون exception). الـ CPU limit بيعمل throttling (الـ app بتبطأ مش بتقع). و Environment.ProcessorCount في .NET بتعكس الـ CPU limit، وده بيأثر على حجم الـ thread pool والـ parallelism.
Linux Basics و CLI و Permissions و Bash
أغلب الـ production للـ .NET دلوقتي على Linux (containers). لازم تتعامل بثقة مع الـ shell. مبدأ يونكس: كل حاجة ملف (devices، sockets، processes في /proc)، وأدوات صغيرة بتتركّب مع بعض بـ pipes (|).
| Path | Purpose |
|---|---|
/ | root of the file system |
/etc | configuration files |
/var/log | logs (/var/log/syslog, nginx logs…) |
/home/<user> · /tmp | user files · temporary files |
/proc · /sys | virtual FS exposing kernel/process info (/proc/<pid>/status) |
/usr/bin · /opt | binaries · optional apps (/opt/myapp) |
أدوات الـ CLI الأساسية
# --- navigate & inspect ---
pwd; ls -lah /var/log; cd /opt/myapp
tail -n 100 -f app.log # follow a log live (Ctrl+C to stop)
less +G app.log # page through, jump to end
# --- grep: find lines (-r recursive, -n line numbers, -i ignore case, -C 3 context) ---
grep -rn "NullReferenceException" /var/log/myapp/
grep -i -C 3 "timeout" app.log
# --- awk: columns. Top 10 client IPs in an nginx access log ---
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10
# --- sed: stream editor. Replace text; print a line range ---
sed -i 's/Server=localhost/Server=db.internal/g' appsettings.Production.json
sed -n '120,140p' app.log
# --- processes ---
ps aux | grep dotnet # who's running, PID, CPU%, MEM%
top # live view (htop is nicer). Press M = sort by memory, P = CPU
kill -15 4120 # SIGTERM: ask nicely (graceful shutdown)
kill -9 4120 # SIGKILL: forced (no cleanup!)
# --- systemd services & logs ---
systemctl status myapp
sudo systemctl restart myapp
journalctl -u myapp --since "10 min ago" -f # service logs, follow
journalctl -u myapp -p err -n 50 # last 50 error-level lines
# --- disk / memory / network ---
df -h; du -sh /var/log/*; free -m
ss -tlnp # listening ports + owning process- الـ pipe
|بيوصّل stdout بتاع أمر بـ stdin بتاع التاني. المثال بتاع awk: استخرج العمود الأول (IP) ⇒sortيجمّع المتشابه ⇒uniq -cيعد ⇒sort -rnترتيب تنازلي ⇒headأعلى 10. ده pipeline كامل بدون برنامج. SIGTERM (15)بتسمح للتطبيق ينظف ويقفل بهدوء (graceful shutdown)، أماSIGKILL (9)بيقتل فوراً ومش ممكن التطبيق يمسكها. ابدأ دايماً بـ 15.journalctl -uبيقرا logs الـ service اللي تحت systemd (stdout/stderr للتطبيق بتروح هناك).
Permissions والمستخدمين
كل ملف له owner وgroup وثلاث مجموعات صلاحيات: للـ owner (u)، للـ group (g)، للباقي (o). كل مجموعة: r=4 (قراءة)، w=2 (كتابة)، x=1 (تنفيذ، أو دخول للمجلد).
ls -l run.sh # -rw-r--r-- 1 deploy app 120 run.sh
chmod 755 run.sh # owner rwx, group r-x, others r-x (scripts / executables)
chmod 644 notes.txt # owner rw-, others r-- (normal files)
chmod 600 id_rsa # private keys: owner only (ssh refuses looser perms)
chmod +x run.sh # just add execute
chown deploy:app /opt/myapp -R # change owner:group recursively
id # who am I? uid, gid, groups
sudo -u appuser dotnet MyApp.dll # run as another user
# NEVER run your web app as root: a bug (RCE) becomes full control of the machine.Bash Scripting Basics
#!/usr/bin/env bash
set -euo pipefail # -e stop on error, -u error on unset variable, -o pipefail fail if any pipe stage fails
APP_DIR="/opt/myapp"
BACKUP_DIR="/var/backups/myapp"
VERSION="${1:?Usage: deploy.sh <version>}" # required argument
log() { echo "[$(date +%H:%M:%S)] $*"; }
log "Backing up current release"
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/myapp-$(date +%F).tgz" -C "$APP_DIR" .
log "Deploying $VERSION"
if curl -fsS -o /tmp/app.zip "https://artifacts.internal/myapp/$VERSION.zip"; then
unzip -oq /tmp/app.zip -d "$APP_DIR"
else
log "Download failed"; exit 1
fi
sudo systemctl restart myapp
for i in {1..10}; do
if curl -fs http://localhost:8080/health >/dev/null; then log "Healthy"; exit 0; fi
sleep 2
done
log "Health check failed"; exit 1set -euo pipefailهو أهم سطر: من غيره السكريبت بيكمل بعد أخطاء ويعمل أضرار صامتة."${1:?...}"بيطلب المعامل الأول وإلا بيطبع رسالة ويقف. دايماً حط المتغيرات بين" "لتجنب مشاكل المسافات.curl -fsS:-fبيفشل على HTTP errors،-sهادي،-Sيعرض الخطأ. الـexitcode هو اللي بيحدد النجاح (0) أو الفشل (غير صفر) وبيتعمل عليهif.- السكريبت بيعمل backup → deploy → restart → health check، وبيرجّع كود فشل لو الـ health check فشل (عشان الـ CI يعرف).
Processes والـ Environment Variables جوه Containers و cgroups و namespaces
الـ container مش VM. هو process عادية على الـ host بس الـ kernel بيخدعها وبيحدد مواردها باستخدام ميزتين: namespaces (بتحدد «إيه اللي تشوفه») وcgroups (بتحدد «كام تستخدم»). Docker بيبني فوقهم.
Namespaces
pid (الـ process يشوف نفسه PID 1)، net (شبكة خاصة)، mnt (file system خاص)، uts (hostname)، ipc، user (mapping للمستخدمين). العزل ده «رؤية» مش أمان مطلق (kernel مشترك).
cgroups (control groups)
بتحدد وتراقب استهلاك المجموعة: ذاكرة، CPU، I/O، عدد الـ processes. تخطي الذاكرة ⇒ OOM kill. تخطي CPU ⇒ throttling (تبطيء).
# Limits are cgroup settings, nothing more
docker run -d --name api --memory=512m --cpus=1.5 -e ASPNETCORE_ENVIRONMENT=Production \
-e ConnectionStrings__Default="Host=db;Database=shop" -p 8080:8080 myorg/shop-api:1.0
docker exec api cat /sys/fs/cgroup/memory.max # 536870912 (cgroup v2: 512MB in bytes)
docker exec api cat /sys/fs/cgroup/cpu.max # 150000 100000 (1.5 cores)
docker exec api ps aux # the app is PID 1 inside the container
docker exec api printenv | grep -E 'ASPNETCORE|Connection'
# Same process, seen from the HOST (different PID, same kernel)
ps aux | grep MyApp.dll
# Namespaces in action: start a shell in new PID + mount namespaces without Docker
sudo unshare --pid --fork --mount-proc bash -c 'ps aux' # shows only 2 processes--memoryو--cpusبيتترجموا لملفات cgroup (memory.max,cpu.max). الـ container مش بيعمل «حجز» لـ RAM، دي مجرد حدود.-eبيحقن environment variables في process الـ container. في ASP.NET Core الـ config provider للـ environment بيحوّل الـ__(underscore مزدوج) لـ:فـConnectionStrings__Default=ConnectionStrings:Default. بيتفوّق علىappsettings.json، فهو الطريقة القياسية للـ secrets/config في الـ containers (من أسرار الـ orchestrator مش من الـ image).- التطبيق هو PID 1 جوه الـ container: يعني هو اللي بيستقبل
SIGTERMلماdocker stopيحصل. لو مبيتعاملش معاه الـ container بتتقتل بعد 10 ثواني (SIGKILL). الـ .NET Generic Host بيلتقط SIGTERM ويعمل graceful shutdown (HostOptions.ShutdownTimeoutالافتراضي 30 ثانية في النسخ الحديثة، فظبطه أقل من grace period بتاع الـ orchestrator). - PID 1 مسؤول كمان عن تنظيف الـ zombie processes؛ لو بتشغّل child processes استخدم
--initفي Docker. - الـ
unshareبيثبت إن الـ container مجرد process في namespaces جديدة: مفيش «ماكينة» ثانية.
(1) الـ app بتتقتل من غير exception ⇒ OOMKilled (docker inspect ⇒ OOMKilled: true). ارفع الـ limit أو قلل الاستهلاك. (2) بطء مع CPU limit صغير ⇒ throttling؛ شوف cpu.stat. (3) الـ app مبتقفلش بهدوء ⇒ مش بتستقبل SIGTERM (الـ shell form في CMD بيحط shell قبلها)، استخدم exec form: ENTRYPOINT ["dotnet","MyApp.dll"]. (4) secrets اتكتبت جوه الـ image أو في env variables بتتسرّب في الـ logs.
أخطاء شائعة وتشخيص
| العَرَض | السبب | التشخيص / الحل |
|---|---|---|
| Latency عالية والـ CPU قليل | Thread pool starvation من blocking calls | dotnet-counters: threadpool-queue-length. شيل .Result/.Wait()، استخدم async |
| أرقام عشوائية / داتا مفقودة تحت load | Race condition على shared state | حدد الـ mutable shared state (غالباً في Singleton). Interlocked / lock / Concurrent* / immutable |
| Requests معلقة من غير error | Deadlock | dotnet-dump + clrstack -all. ثبّت ترتيب الـ locks، ومتستخدمش lock حول await |
| الـ app بتقع في Docker من غير log | OOMKilled | docker inspect، راقب الـ working set، ارفع الـ limit أو قلل الـ allocations |
Too many open files | تسريب file handles / sockets أو limit صغير | lsof -p، using / IHttpClientFactory، رفع ulimit -n |
StackOverflowException | recursion بلا حد أو عميقة | حوّلها لـ iterative بـ Stack<T>. مش ممكن تمسكها بـ catch |
| Memory بتزيد باستمرار | Leak (objects عالقة في static/event handler/cache بلا حد) | dotnet-gcdump / dotnet-dump وقارن الـ heap بين لقطتين |
Permission denied | صلاحيات ملف/مستخدم غلط | ls -l، id، chown/chmod مع أقل صلاحية ممكنة |
Knowledge Check
أهم النقاط
- Process = ذاكرة معزولة. Thread = خط تنفيذ بيشارك الـ heap مع باقي threads الـ process وده مصدر الـ race conditions.
- الـ context switch والـ syscalls ليهم تكلفة؛ threads أكتر من الـ cores مش بتسرّع الشغل الـ CPU-bound، والـ batching بيقلل الـ syscalls.
- Stack سريع ومحدود وخاص بالـ thread، Heap مشترك ومدار بالـ GC. Virtual memory بتديك عزل و demand paging؛ الـ page faults من الـ disk غالية.
- Race condition = بيانات مشتركة + مفيش synchronization. الحل: عدم المشاركة أو Interlocked أو lock أو immutability.
- Deadlock يحتاج circular wait. كسره بترتيب ثابت للـ locks أو timeouts. وفي async: async all the way.
- Async I/O بيحرر الـ threads أثناء الانتظار. Blocking في ASP.NET Core ⇒ thread pool starvation.
- Container = process + namespaces + cgroups. الـ limits بتأثر على الـ GC والـ thread pool، والتخطي ⇒ OOMKilled.
أسئلة مفاهيمية
ليه lock مينفعش يتحط حوالين await؟
الـ lock مربوط بالـ thread اللي مسكه، والـ await ممكن يكمل على thread تاني فمستحيل يعمل release صح، لذلك الـ compiler بيمنعه. للـ async استخدم SemaphoreSlim(1,1) مع WaitAsync.
فرّق بين Mutex و SemaphoreSlim و lock.
lock: thread واحد، داخل process، سريع. Mutex: thread واحد لكن على مستوى OS فبيشتغل بين processes (أبطأ). SemaphoreSlim(N): N threads، وبيدعم async.
إيه الفرق بين الـ virtual size والـ working set؟ وأيهم بيتحاسب عليه الـ container؟
الـ virtual size هو الـ address space المحجوز، والـ working set هو اللي في الـ RAM فعلاً. الـ cgroup بيحاسب على الذاكرة الفعلية المستهلكة (RSS + page cache تبع الـ container)، مش الـ virtual.
ليه Environment.ProcessorCount مهم في container؟
لأنه بيحدد حجم الـ thread pool الابتدائي ودرجة الـ parallelism. في .NET بيعكس CPU limit الخاص بالـ container (مش cores الـ host)، فلو limit = 1 core، الـ pool ابتدائيته صغيرة و blocking calls هتخنقه بسرعة.
الـ Heisenbug معناه إيه؟ ومثال؟
bug بيختفي أو بيتغير لما تحاول تراقبه (debugger/log بيغيّر التوقيت). مثال كلاسيكي: race condition، أو memory corruption.
قراءة كود
public class Cache
{
private readonly Dictionary<string, string> _items = new();
public string GetOrAdd(string key, Func<string> factory)
{
if (!_items.ContainsKey(key))
_items[key] = factory();
return _items[key];
}
}
// Registered as Singleton and used from many requests concurrentlyإيه المشاكل؟ وإزاي تصلحها؟
(1) Dictionary غير thread-safe: كتابة متزامنة ممكن تفسد البنية الداخلية (exception، infinite loop، أو بيانات مفقودة). (2) check-then-act: threads اتنين ممكن يعدّوا ContainsKey مع بعض فيشغّلوا factory() مرتين. الحل: ConcurrentDictionary.GetOrAdd(key, k => factory()) (لاحظ إن الـ factory ممكن تتنفذ أكتر من مرة، فاستخدم Lazy<T> كـ value لو لازم مرة واحدة) أو lock حول العملية كلها.
app.MapGet("/report", (ReportService svc) =>
{
var data = svc.LoadAsync().Result; // returns Task<Report>
return Results.Ok(data);
});التشخيص والحل؟
.Result بيحجز thread من الـ pool طول فترة الـ I/O ⇒ مع load عالي الـ pool يتشبع (starvation) و latency تنفجر رغم CPU فاضي. الحل: async (ReportService svc) => Results.Ok(await svc.LoadAsync()) وتمرير CancellationToken.
أسئلة إنترفيو شائعة
اشرح الفرق بين process و thread و task في .NET.
Process: ذاكرة معزولة. Thread: كيان تنفيذ في الـ OS. Task: تجريد لعملية (ممكن CPU أو I/O) بتتجدول غالباً على thread من الـ ThreadPool، وممكن يكون مفيش thread خالص أثناء انتظار الـ I/O.
امتى تستخدم Parallel.ForEach وامتى async/await؟
Parallel للـ CPU-bound المقسّم على cores. async/await للـ I/O-bound (DB، HTTP، ملفات) لتحرير الـ threads. الخلط الشائع: Parallel.ForEach بداخله I/O blocking، أو Task.Run لتغليف I/O.
الـ container أمني زي الـ VM؟
لأ. الـ VM عنده kernel مستقل (عزل أقوى عن طريق hypervisor). الـ container بيشارك الـ kernel مع الـ host، فثغرة kernel أو container escape أخطر؛ عشان كده بنزود: non-root user، read-only filesystem، seccomp/AppArmor، وإسقاط الـ capabilities.
لو الـ app بتبطأ بعد ساعات من التشغيل، تدور على إيه؟
تسريب موارد (memory/handles/threads/connections)، تراكم في cache بلا حد، عدد threads بيزيد، GC pauses بسبب heap كبير، أو starvation تدريجي. أبدأ بـ dotnet-counters (GC، thread pool، exceptions) ثم dump/gcdump للمقارنة.
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
التوثيق الرسمي — Official documentation
مصادر تعليمية ومتقدمة — Third-party & advanced reading
خريطة التغطية: 24 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.