0% found this document useful (0 votes)
0 views12 pages

Ex 5

The document provides an overview of threading in C#, covering basic to advanced concepts, including thread creation, lifecycle, synchronization techniques, and advanced features like thread pooling and tasks. It emphasizes the importance of proper synchronization to avoid race conditions and improve application performance. The article serves as a comprehensive guide for developers looking to enhance their understanding of concurrency in C#.

Uploaded by

gangursahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views12 pages

Ex 5

The document provides an overview of threading in C#, covering basic to advanced concepts, including thread creation, lifecycle, synchronization techniques, and advanced features like thread pooling and tasks. It emphasizes the importance of proper synchronization to avoid race conditions and improve application performance. The article serves as a comprehensive guide for developers looking to enhance their understanding of concurrency in C#.

Uploaded by

gangursahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

C# Threading: From Basic to Advanced


Laks Tutor · Follow
2 min read · Aug 30, 2023

Listen Share

Threading is a fundamental concept in computer science that allows multiple


operations to run concurrently, making the most of available resources and
improving application performance. In C#, the System.Threading namespace
provides a rich set of classes to manage and control threads. In this blog post, we'll
explore threading in C# from basic to advanced concepts, with examples.

1. Basics of Threading

What is a Thread?
A thread is the smallest unit of execution within a process. Each thread has its own
stack and local variables. In C#, the main thread is the one that executes the Main

method. However, you can create additional threads to run tasks in parallel.

Creating a Thread
To create a thread in C#, you can use the Thread class from the System.Threading

namespace.

using System;
using System.Threading;

class Program
{
static void Main()
{
Thread newThread = new Thread(new ThreadStart(PrintNumbers));
newThread.Start();
}

https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 1/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

static void PrintNumbers()


{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
}

In the above example, we created a new thread that runs the PrintNumbers method.

2. Thread Lifecycle
A thread goes through various states in its lifecycle:

Unstarted: The thread is created but not started.

Running: The thread is currently executing.

WaitSleepJoin: The thread is blocked, waiting for some condition.

Stopped: The thread has completed execution or has been aborted.

You can check the state of a thread using the ThreadState property.

3. Thread Synchronization
When multiple threads access shared resources, there's a potential for race
conditions. To prevent this, you can use synchronization techniques.

Lock
The lock keyword ensures that one thread does not enter a critical section while
another thread is in the critical section.

private static object _lock = new object();

static void SafePrint(string message)


{
lock (_lock)
{
Console.WriteLine(message);
}
}

https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 2/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

Mutex
A mutex is similar to a lock but can work across multiple processes.

using (Mutex mutex = new Mutex(false, "MyMutexName"))


{
mutex.WaitOne();
// Critical section
mutex.ReleaseMutex();
}

4. Advanced Threading Concepts

Thread Pooling
Instead of creating and destroying threads, which can be resource-intensive, you
can use a thread pool. The ThreadPool class allows you to queue tasks without
managing individual threads.

ThreadPool.QueueUserWorkItem((state) => {
Console.WriteLine("This is running in a thread pool thread.");
});

Tasks
Tasks represent an asynchronous operation. They are built on top of the thread pool
and provide a higher-level way to work with concurrency.

using System.Threading.Tasks;

Task.Run(() => {
Console.WriteLine("This is running in a task.");
});

Parallel Loops
The Parallel class provides a way to parallelize loops, making them run faster on
multi-core systems.

https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 3/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

Parallel.For(0, 10, i => {


Console.WriteLine($"Parallel loop iteration: {i}");
});

Conclusion
Threading in C# offers a powerful way to improve application performance by
leveraging concurrency. Whether you're just starting out or looking to dive deep into
advanced concepts, the System.Threading namespace provides all the tools you
need. Remember to always be cautious when working with threads, as improper
synchronization can lead to unpredictable results. Happy coding!

Threading Csharp Programming

Follow

Written by Laks Tutor


131 Followers

Software Architect & .NET expert. Specializing in Docker & Kubernetes. Freelance corporate trainer. Shaping
tech & sharing insights on Medium.

More from Laks Tutor

https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 4/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

Open in app Sign up Sign in

Search

Laks Tutor

C# IEnumerable and IEnumerator: An In-depth Exploration from Basics


to Advanced
Introduction

3 min read · Aug 15, 2023

14

Laks Tutor

C# Builder Pattern: Constructing Objects Step-by-Step


https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 5/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

Introduction

2 min read · Aug 15, 2023

53 1

Laks Tutor

Strategy Pattern in C#: From Basics to Advanced


The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm’s
implementation at runtime. Instead of…

3 min read · Aug 17, 2023

57

https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 6/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

Laks Tutor

Implementing Canary Deployments in Kubernetes: A Comprehensive


Guide
Introduction

3 min read · Aug 15, 2023

14

See all from Laks Tutor

Recommended from Medium

https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 7/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

Niraj Ranasinghe

Understanding Concurrency in C# with Threads, Tasks and ThreadPool


Concurrency in C# involves the simultaneous execution of tasks within a program, using
features like threads and tasks. It’s like having…

12 min read · Dec 7, 2023

94

Shahzad Aslam

C# Polymorphism with Examples


https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 8/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

Polymorphism mean many forms that we usually archived with static binding and dynamic
binding.. In static polymorphism, the response to a…

· 4 min read · Apr 12, 2024

30

Lists

Staff Picks
636 stories · 957 saves

Stories to Help You Level-Up at Work


19 stories · 601 saves

Self-Improvement 101
20 stories · 1766 saves

Productivity 101
20 stories · 1627 saves

Konstantin Fedorov

Stack vs. Heap: Mastering Memory Management in C#


When diving into the world of C# programming, it’s impossible to avoid encountering the
concepts of stack and heap memory. These two types…

https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 9/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

7 min read · Mar 8, 2024

125

Sergio Gonzalez

Improve Conditional Logic in C# (strategy pattern)


In programming, especially for beginners, understanding how to manage and optimize
conditional logic is crucial. Conditional structures…

5 min read · Apr 15, 2024

130 3

https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 10/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

Shah Rukh Khan

Understanding the Differences Between IEnumerable and IQueryable in


C#
In the world of C# programming, managing collections and data queries efficiently is crucial.
Two key interfaces that facilitate this are…

3 min read · Jan 18, 2024

43 1

Tarik Berkovac in Towards Dev

https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 11/12
5/10/24, 4:15 PM C# Threading: From Basic to Advanced | by Laks Tutor | Medium

Modular Monolith Architecture PART I


The problem with typical 3-layer architecture is that we can get spaghetti code pretty fast. A
more interesting method to develop software…

8 min read · Apr 25, 2024

18 1

See more recommendations

https://medium.com/@lexitrainerph/c-threading-from-basic-to-advanced-84927e502a38 12/12

You might also like