SlideShare una empresa de Scribd logo
1 de 20
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
End of Presentation

Más contenido relacionado

La actualidad más candente

Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreadingjehan1987
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Thread model of java
Thread model of javaThread model of java
Thread model of javamyrajendra
 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javajunnubabu
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead ProgrammingNishant Mevawala
 

La actualidad más candente (20)

Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Java threads
Java threadsJava threads
Java threads
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
 
.Net Threading
.Net Threading.Net Threading
.Net Threading
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 

Destacado

Threading in c#
Threading in c#Threading in c#
Threading in c#gohsiauken
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLArie Leeuwesteijn
 
Multi threading design pattern
Multi threading design patternMulti threading design pattern
Multi threading design patternYan Wang
 
C# Advanced L04-Threading
C# Advanced L04-ThreadingC# Advanced L04-Threading
C# Advanced L04-ThreadingMohammad Shaker
 
C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingPraveen Prajapati
 
Asynchronous Programming with C#
Asynchronous Programming with C#Asynchronous Programming with C#
Asynchronous Programming with C#Muhammed Tahiroglu
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event HandlingJussi Pohjolainen
 
Quy tắc thiết kế giao diện và viết code C#
Quy tắc thiết kế giao diện và viết code C#Quy tắc thiết kế giao diện và viết code C#
Quy tắc thiết kế giao diện và viết code C#An Nguyen
 
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 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 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 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...MasterCode.vn
 
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPTBÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPTMasterCode.vn
 

Destacado (14)

Threading in c#
Threading in c#Threading in c#
Threading in c#
 
Thread
ThreadThread
Thread
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
 
Real time web
Real time webReal time web
Real time web
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Multi threading design pattern
Multi threading design patternMulti threading design pattern
Multi threading design pattern
 
C# Advanced L04-Threading
C# Advanced L04-ThreadingC# Advanced L04-Threading
C# Advanced L04-Threading
 
C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programming
 
Asynchronous Programming with C#
Asynchronous Programming with C#Asynchronous Programming with C#
Asynchronous Programming with C#
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
Quy tắc thiết kế giao diện và viết code C#
Quy tắc thiết kế giao diện và viết code C#Quy tắc thiết kế giao diện và viết code C#
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 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 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 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
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPTBÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
 

Similar a Threads c sharp

OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxArulmozhivarman8
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Java class 6
Java class 6Java class 6
Java class 6Edureka!
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Sachintha Gunasena
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfKrystian Zybała
 
Threads and Synchronization in c#
Threads and Synchronization in c#Threads and Synchronization in c#
Threads and Synchronization in c#Rizwan Ali
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
C#: Understanding ConfigureAwait(false)
C#: Understanding ConfigureAwait(false)C#: Understanding ConfigureAwait(false)
C#: Understanding ConfigureAwait(false)Shuhei Eda
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
 

Similar a Threads c sharp (20)

Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java class 6
Java class 6Java class 6
Java class 6
 
MULTI THREADING.pptx
MULTI THREADING.pptxMULTI THREADING.pptx
MULTI THREADING.pptx
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
Java Thread
Java ThreadJava Thread
Java Thread
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
 
Threads and Synchronization in c#
Threads and Synchronization in c#Threads and Synchronization in c#
Threads and Synchronization in c#
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
C#: Understanding ConfigureAwait(false)
C#: Understanding ConfigureAwait(false)C#: Understanding ConfigureAwait(false)
C#: Understanding ConfigureAwait(false)
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 

Último

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 

Último (20)

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 

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
  • 16.
  • 17.
  • 18.
  • 19.