Threads and synchronization in C# visual programming.pptx

azkamurat 369 views 8 slides Jul 04, 2024
Slide 1
Slide 1 of 8
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8

About This Presentation

Threading synchronization in c#


Slide Content

Threads and synchronization in C#

Threads and synchronization are crucial concepts in C# for creating concurrent applications. Threads: A thread is the smallest unit of a process that can be scheduled by the operating system. In C#, the System.Threading namespace provides the classes and methods needed to work with threads. Creating and Starting a Thread You can create and start a thread using the Thread class. Here's an example:

using System; using System.Threading ; class Program { static void Main() { Thread thread = new Thread(new ThreadStart ( DoWork )); thread.Start (); } static void DoWork () { Console.WriteLine ("Work is being done on a separate thread."); } }

Synchronization When multiple threads access shared resources concurrently, you need to synchronize their access to avoid data corruption or inconsistency. C# provides several synchronization primitives to help with this: Lock The lock statement in C# is a way to ensure that a block of code is executed by only one thread at a time. It is a shorthand for Monitor.Enter and Monitor.Exit .

How Thread Synchronization is Achieved in C #? Synchronization in C# can be achieved in multiple ways. One of the ways to achieve Synchronization in C# is by using the feature of lock, which locks the access to a block of code within the locked object. When a thread locks an object, no other thread can access the block of code within the locked object. Only when a thread releases the lock, then it is available for other threads to access it. In C# Language, every object has a built-in lock. By using the feature of Synchronization, we can lock an object. Locking an object can be done by using the lock keyword, and the following is the syntax to use the lock.

class Program { private static readonly object _lock = new object(); static void Main() { Thread thread1 = new Thread(new ThreadStart ( DoWork )); Thread thread2 = new Thread(new ThreadStart ( DoWork )); thread1.Start(); thread2.Start(); } static void DoWork () { lock (_lock) { // Critical section Console.WriteLine ("Thread {0} is executing DoWork ", Thread.CurrentThread.ManagedThreadId ); } } }

Monitor The Monitor class provides a more complex and flexible way to work with locks than the lock statement.

class Program { private static readonly object _lock = new object(); static void Main() { Thread thread1 = new Thread(new ThreadStart ( DoWork )); Thread thread2 = new Thread(new ThreadStart ( DoWork )); thread1.Start(); thread2.Start(); } static void DoWork () { Monitor.Enter (_lock); try { // Critical section Console.WriteLine ("Thread {0} is executing DoWork ", Thread.CurrentThread.ManagedThreadId ); } finally { Monitor.Exit (_lock); } } }