Thursday, October 12, 2017

Multithreading concept in c#

Difference in keyword used -

Concurrent
several thhings going in parallel
several things happening at once
might or might not be mutithread

Mutithreading
uses OS capabuility to porcess multiple operations
Multiple execution context
more than 1 thread, might or might not be concurrent

Parallel
multi simultaneous computations
more on hardware level -
multi core CPU - multiple processing at once

Asynchronous
not having to wait

Context Switch -
It is OS level concept. When the thread/process are executing any code and CPU needs to execute some other instruction, then it stores the state of current thread like register state and all in memory and store the other thread.
Ref - http://www.linfo.org/context_switch.html

Process, Thread and Apartment
Ref - https://msdn.microsoft.com/library/windows/desktop/ms693344.aspx

An application domain forms an isolation boundary for security, versioning, reliability, and unloading of managed code. A thread is the operating system construct used by the common language runtime to execute code. At run time, all managed code is loaded into an application domain and is run by one or more managed threads.
There is not a one-to-one correlation between application domains and threads. Several threads can execute in a single application domain at any given time, and a particular thread is not confined to a single application domain. That is, threads are free to cross application domain boundaries; a new thread is not created for each application domain.

Understanding STA & MTA-
The COM threading model is called an "apartment" model, where the execution context of initialized COM objects is associated with either a single thread (Single Thread Apartment) or many threads (Multi Thread Apartment). In this model, a COM object, once initialized in an apartment, is part of that apartment for the duration of its runtime.

The STA model is used for COM objects that are not thread safe. That means they do not handle their own synchronization. A common use of this is a UI component. So if another thread needs to interact with the object (such as pushing a button in a form) then the message is marshalled onto the STA thread. The windows forms message pumping system is an example of this.

If the COM object can handle its own synchronization then the MTA model can be used where multiple threads are allowed to interact with the object without marshalled calls.

No comments:

Post a Comment