Threads

Added in .NET 1.1
A thread is a unit of scheduling
Threads can only have one task running at a time.
Threads typically represent multiple flows of execution in an application (or process)
Each thread can run in a separate processor on a multi-processor computer.
By default each thread executes independently


System.Threading.Thread myThread; 
myThread = new System.Threading.Thread(delegate() {});
myThread.Start();

Thread Class

The Thread class is used for creating and manipulating a thread in Windows.



Application Domains

An App Domain can contain one or more threads.
Threads can cross between different App Domains.
Applications > Application Domains


STA - Single Threaded Apartment


System.Threading.Thread.CurrentThread.TrySetApartmentState

This sets the apartment state of a thread.
(System.Threading.ApartmentState.STA)
Returns true if the apartment state is set
Returns true if the apartment state is not set



Single Threaded Apartment

The STA (Single Threaded Apartment) can have only one thread.
When an object created on a STA thread is called from another thread, this other thread posts windows messages into the message queue of the STA thread.


You can use Queues with multi-threading in .NET but you must use the necessary lock statements.


Lots of windows code requires you to follow STA
such as: clipboard, drag and drop, windows common dialog boxes, UI thread for WPF, windows forms, multiple windows


Threads are initialized as ApartmentState.MTA by default.
The apartment state cannot be changed once the thread has been created.


Communication between apartments is done via marshalling


System.Threading.Thread.CurrentThread 

Thread Safe Blocking Queue.
Interlocked classes




Methods

Abort
GetApartmentState
GetData
Interrupt
Join
Resume
SetApartmentState - sets the apartment state of a thread before it is started
SetData
Sleep
Suspend
Yield


Properties

CurrentContext
CurrentThread
IsAlive
IsBackground
IsThreadPoolThread
Name
Priority
ThreadState



A managed thread can create a single threaded apartment that allows only one thread or a multi-threaded apartment that allows more than one thread.
You can control which type of apartment will be used in a thread by specifying the ApartmentState property before the thread is started.





© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext