SlideShare a Scribd company logo
C# Threads

             Jim Fawcett
CSE681 – Software Modeling and Analysis
               Fall 2005
Thread Class

•   Every Win32 thread is passed a function to run when created.

    – When the thread returns from the function it terminates.

•   In C#, Threads are managed by the System.Threading.Thread
    class.

    – C# threads are passed a static or instance function of some C#
      class using a standard delegate of type ThreadStart.
Starting C# Threads

•   Thread thread =
       new Thread(new ThreadStart(ThreadFunc));

•   thread.Start();

•   ThreadFunc can be:
    – Static or instance member of the class instance that created the thread
    – Static or instance member of some other class, e.g.:

       ThreadStart(SomeClass.aStaticFunction);
       ThreadStart(someClassInstance.aNonStaticFunction);
Thread States

•   A thread that has been started, but not yet terminated can be in
    one of the following states:
     –   Running
     –   Waiting to run
     –   Suspended
     –   Blocked
Thread Properties

•   IsBackground – get, set
     – Process does not end until all Foreground threads have ended.
     – Background threads are terminated when application ends.
•   CurrentThread – get, static
     – Returns thread reference to calling thread

•   IsAlive – get
     – Has thread started but not terminated?

•   Priority – get, set
     – Highest, AboveNormal, Normal, BelowNormal, Lowest
•   ThreadState – get
     – Unstarted, Running, Suspended, Stopped, WaitSleepJoin, ..
Sharing Resources

•   A child thread often needs to communciate with its parent thread. It does
    this via some shared resource, like a queue.


                              Parent Thread


                     Sending Message to Child




                                                               Child Thread


                                                Shared Queue


                                                               Receiving Message from
                                                                       Parent
Synchronization

•   When two or more threads share a common resource access needs
    to be serialized - a process called synchronization.
    – Consider the shared queue on the previous slide. Should the parent
      start to enqueue an element in an empty queue, but have its time-slice
      expire before finishing, the queues links are in an undefined state.

    – Now, if the child thread wakes up, and attempts to dequeue an element
      the result is undefined.
Synchronization with C# Lock

// send messages to child thread

     string msg = "";
     for(int i=0; i<50; ++i)
     {
       msg = "message #" + i.ToString();
       Console.Write("n Sending {0},",msg);

         // Enqueuing changes links so must lock

         lock(demo.threadQ) { demo.threadQ.Enqueue(msg); }

         // control writer speed - twice as fast as reader

         Thread.Sleep(50);
     }

     lock(demo.threadQ) { demo.threadQ.Enqueue("end"); }

     child.Join();
     Console.Write(
       "nn child thread state = {0}nn",child.ThreadState.ToString()
     );
Demonstration Program

•   QueuedMessages folder

    – Illustrates communication between parent and child threads using a
      queue.

    – Also illustrates use of C# lock operation.
Other Locking Mechanisms

•   The .Net Threading Library also provides:

     – Monitor
         • Locks an object, like C# lock, but provides more control.
     – Interlocked
         • Provides atomic operations on 32 bit and 64 bit data types, e.g., ints,
           longs, pointers.
     – Mutex
         • Guards a region of code.
         • Can synchronize across process boundaries.
     – AutoResetEvent and WaitOne
         • Allows fine-grained control of the sequencing of thread operations.
     – ReaderWriterLock
         • Locks only when writing, allowing free reads.
Locking Certain Collections

•   ArrayList, Hashtable, Queue, Stack, and other collections provide
    Synchronized() function, supporting high performance locking.

       ArrayList unsync = new ArrayList();
       ArrayList sync = ArrayList.Synchronized(unsynch);

    Your code needs no lock constructs with sync.
Method Decoration

•   Methods can be decorated with a MethodImpl attribute, synchronizing
    access much like a Win32 critical section.

      [MethodImpl (MethodImplOptions.Synchronized)]
       string myMethod(string input)
       {
           …
       }

    Note that this synchronizes a region of code, while lock and Monitor
    synchronize objects.
WinForms and Worker Threads

•   A UI thread is a thread that creates a window. A worker thread
    is a thread spawned by a UI thread to do work in the
    background while the UI thread services UI messages.

•   A worker thread must never access UI functions directly. It
    accesses them through Form’s Invoke, BeginInvoke, and
    EndInvoke functions, passing a delegate as an argument.
BeginInvoke Example

for (i = 1; i <= 25; i++)
{
  s = "Step number " + i.ToString() + " executed";
  Thread.Sleep(400);

    // Make asynchronous call to main form.

    //   MainForm.AddString function runs in main thread
    //   because we activated the delegate through form's
    //   Invoke (synchronous) or BeginInvoke (asynchronous) functions.
    //   To make synchronous call use Invoke.

    m_form.BeginInvoke(m_form.m_DelegateAddString, new Object[] {s});

    // check if thread is cancelled
    if ( m_EventStop.WaitOne(0, true) )
    {
      // clean-up operations may be placed here
      // ...                                                      Delegate arguments
                                                                  passed as an array of
        // inform main thread that this thread stopped
        m_EventStopped.Set();                                     objects
        return;
    }
}
Demonstration Programs

•   ProcessDemo and ProcessDemoWin32
    – Illustrates creating a child process
•   QueuedMessages
    – Illustrates communication between threads using queues and the
      C# lock operation.
•   FormInvokeDemo folder
    – A more interesting demonstration of the above.
•   WorkerThread folder
    – Simple Demonstration of UI and Worker thread communication
      using Form.Invoke(…)
•   ThreadPoolDemo folder
    – Illustrates how to use the ThreadPool to run functions
Threads c sharp
Threads c sharp
Threads c sharp
Threads c sharp
End of Presentation

More Related Content

PPTX
Threading
PPT
Threads c sharp
PPT
Intro To .Net Threads
PPTX
PPTX
Threading in C#
PPTX
.NET Multithreading/Multitasking
PPT
Threads And Synchronization in C#
PPTX
.NET: Thread Synchronization Constructs
Threading
Threads c sharp
Intro To .Net Threads
Threading in C#
.NET Multithreading/Multitasking
Threads And Synchronization in C#
.NET: Thread Synchronization Constructs

What's hot (20)

PPTX
Java Thread & Multithreading
PPT
Java Threads
ODP
Multithreading Concepts
PPTX
PPT
Runnable interface.34
PDF
Java threads
PPTX
Multithreading
PPT
Learning Java 3 – Threads and Synchronization
PPT
Chap2 2 1
PPT
Java And Multithreading
PPTX
Thread model of java
PDF
.Net Threading
PPTX
Multi threading
PPTX
Multi-threaded Programming in JAVA
PPT
Java Multithreading
PPTX
Multithreading in java
PPTX
Multithread Programing in Java
PPT
Thread model in java
PPTX
Java Multi Thead Programming
PPTX
Threads in Java
Java Thread & Multithreading
Java Threads
Multithreading Concepts
Runnable interface.34
Java threads
Multithreading
Learning Java 3 – Threads and Synchronization
Chap2 2 1
Java And Multithreading
Thread model of java
.Net Threading
Multi threading
Multi-threaded Programming in JAVA
Java Multithreading
Multithreading in java
Multithread Programing in Java
Thread model in java
Java Multi Thead Programming
Threads in Java
Ad

Viewers also liked (14)

PDF
Threading in c#
PPTX
Async and parallel patterns and application design - TechDays2013 NL
PDF
Real time web
PDF
Concurrency
PPTX
Multi threading design pattern
PDF
C# Advanced L04-Threading
PPTX
C# 5 deep drive into asynchronous programming
PDF
Asynchronous Programming with C#
PDF
C# Delegates and Event Handling
PPTX
Delegates and events
PDF
Quy tắc thiết kế giao diện và viết code C#
PDF
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
PDF
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
Threading in c#
Async and parallel patterns and application design - TechDays2013 NL
Real time web
Concurrency
Multi threading design pattern
C# Advanced L04-Threading
C# 5 deep drive into asynchronous programming
Asynchronous Programming with C#
C# Delegates and Event Handling
Delegates and events
Quy tắc thiết kế giao diện và viết code C#
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
Ad

Similar to Threads c sharp (20)

PPT
Threads-CShharp.pptsdfsdfsdgdgsdfasdfsdfasdf
PPT
Threads and Synchronization in c#
PPT
Introto netthreads-090906214344-phpapp01
PDF
.NET Multithreading and File I/O
PDF
Sync, async and multithreading
PDF
Intake 38 12
PPT
Multithreading Presentation
PDF
Threading
PPTX
concurrency_c#_public
PPT
Csphtp1 14
PPTX
Multithreading and concurrency.pptx
PPS
09 gui 13
PPTX
Java class 6
PPS
11 iec t1_s1_oo_ps_session_16
PDF
Concurrency and parallel in .net
PDF
Ia+ threading
PDF
Other Approaches (Concurrency)
PPTX
Multithreading in java
ODP
Concept of thread
Threads-CShharp.pptsdfsdfsdgdgsdfasdfsdfasdf
Threads and Synchronization in c#
Introto netthreads-090906214344-phpapp01
.NET Multithreading and File I/O
Sync, async and multithreading
Intake 38 12
Multithreading Presentation
Threading
concurrency_c#_public
Csphtp1 14
Multithreading and concurrency.pptx
09 gui 13
Java class 6
11 iec t1_s1_oo_ps_session_16
Concurrency and parallel in .net
Ia+ threading
Other Approaches (Concurrency)
Multithreading in java
Concept of thread

Recently uploaded (20)

PPTX
Cell Structure & Organelles in detailed.
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
Cell Types and Its function , kingdom of life
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Pharma ospi slides which help in ospi learning
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Institutional Correction lecture only . . .
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Basic Mud Logging Guide for educational purpose
PDF
RMMM.pdf make it easy to upload and study
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Cell Structure & Organelles in detailed.
O7-L3 Supply Chain Operations - ICLT Program
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Classroom Observation Tools for Teachers
Cell Types and Its function , kingdom of life
Complications of Minimal Access Surgery at WLH
Pharma ospi slides which help in ospi learning
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Institutional Correction lecture only . . .
PPH.pptx obstetrics and gynecology in nursing
Abdominal Access Techniques with Prof. Dr. R K Mishra
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Basic Mud Logging Guide for educational purpose
RMMM.pdf make it easy to upload and study
Module 4: Burden of Disease Tutorial Slides S2 2025
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...

Threads c sharp

  • 1. C# Threads Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2005
  • 2. Thread Class • Every Win32 thread is passed a function to run when created. – When the thread returns from the function it terminates. • In C#, Threads are managed by the System.Threading.Thread class. – C# threads are passed a static or instance function of some C# class using a standard delegate of type ThreadStart.
  • 3. Starting C# Threads • Thread thread = new Thread(new ThreadStart(ThreadFunc)); • thread.Start(); • ThreadFunc can be: – Static or instance member of the class instance that created the thread – Static or instance member of some other class, e.g.: ThreadStart(SomeClass.aStaticFunction); ThreadStart(someClassInstance.aNonStaticFunction);
  • 4. Thread States • A thread that has been started, but not yet terminated can be in one of the following states: – Running – Waiting to run – Suspended – Blocked
  • 5. Thread Properties • IsBackground – get, set – Process does not end until all Foreground threads have ended. – Background threads are terminated when application ends. • CurrentThread – get, static – Returns thread reference to calling thread • IsAlive – get – Has thread started but not terminated? • Priority – get, set – Highest, AboveNormal, Normal, BelowNormal, Lowest • ThreadState – get – Unstarted, Running, Suspended, Stopped, WaitSleepJoin, ..
  • 6. Sharing Resources • A child thread often needs to communciate with its parent thread. It does this via some shared resource, like a queue. Parent Thread Sending Message to Child Child Thread Shared Queue Receiving Message from Parent
  • 7. Synchronization • When two or more threads share a common resource access needs to be serialized - a process called synchronization. – Consider the shared queue on the previous slide. Should the parent start to enqueue an element in an empty queue, but have its time-slice expire before finishing, the queues links are in an undefined state. – Now, if the child thread wakes up, and attempts to dequeue an element the result is undefined.
  • 8. Synchronization with C# Lock // send messages to child thread string msg = ""; for(int i=0; i<50; ++i) { msg = "message #" + i.ToString(); Console.Write("n Sending {0},",msg); // Enqueuing changes links so must lock lock(demo.threadQ) { demo.threadQ.Enqueue(msg); } // control writer speed - twice as fast as reader Thread.Sleep(50); } lock(demo.threadQ) { demo.threadQ.Enqueue("end"); } child.Join(); Console.Write( "nn child thread state = {0}nn",child.ThreadState.ToString() );
  • 9. Demonstration Program • QueuedMessages folder – Illustrates communication between parent and child threads using a queue. – Also illustrates use of C# lock operation.
  • 10. Other Locking Mechanisms • The .Net Threading Library also provides: – Monitor • Locks an object, like C# lock, but provides more control. – Interlocked • Provides atomic operations on 32 bit and 64 bit data types, e.g., ints, longs, pointers. – Mutex • Guards a region of code. • Can synchronize across process boundaries. – AutoResetEvent and WaitOne • Allows fine-grained control of the sequencing of thread operations. – ReaderWriterLock • Locks only when writing, allowing free reads.
  • 11. Locking Certain Collections • ArrayList, Hashtable, Queue, Stack, and other collections provide Synchronized() function, supporting high performance locking. ArrayList unsync = new ArrayList(); ArrayList sync = ArrayList.Synchronized(unsynch); Your code needs no lock constructs with sync.
  • 12. Method Decoration • Methods can be decorated with a MethodImpl attribute, synchronizing access much like a Win32 critical section. [MethodImpl (MethodImplOptions.Synchronized)] string myMethod(string input) { … } Note that this synchronizes a region of code, while lock and Monitor synchronize objects.
  • 13. WinForms and Worker Threads • A UI thread is a thread that creates a window. A worker thread is a thread spawned by a UI thread to do work in the background while the UI thread services UI messages. • A worker thread must never access UI functions directly. It accesses them through Form’s Invoke, BeginInvoke, and EndInvoke functions, passing a delegate as an argument.
  • 14. BeginInvoke Example for (i = 1; i <= 25; i++) { s = "Step number " + i.ToString() + " executed"; Thread.Sleep(400); // Make asynchronous call to main form. // MainForm.AddString function runs in main thread // because we activated the delegate through form's // Invoke (synchronous) or BeginInvoke (asynchronous) functions. // To make synchronous call use Invoke. m_form.BeginInvoke(m_form.m_DelegateAddString, new Object[] {s}); // check if thread is cancelled if ( m_EventStop.WaitOne(0, true) ) { // clean-up operations may be placed here // ... Delegate arguments passed as an array of // inform main thread that this thread stopped m_EventStopped.Set(); objects return; } }
  • 15. Demonstration Programs • ProcessDemo and ProcessDemoWin32 – Illustrates creating a child process • QueuedMessages – Illustrates communication between threads using queues and the C# lock operation. • FormInvokeDemo folder – A more interesting demonstration of the above. • WorkerThread folder – Simple Demonstration of UI and Worker thread communication using Form.Invoke(…) • ThreadPoolDemo folder – Illustrates how to use the ThreadPool to run functions