======
OS facilitates the execution of the program by providing the resources required. each process has a unique process ID
Threads
======
Inside Process, there might be one(main thread) to many lightweight processes has. Those are called threads
Advantages of thread
- to maintain a responsive user interface.
- to split large ask to small task and give deferent cpu to complete them.
Disadvantages
- need to consider thread safe,context switch.
Example 1
Without threads
for print success (on main thread) this will wait for complete TimeConsumingWork
With Threads
Main Thread will not pouse for complete time-consuming task. because it is on another thread
Thread Start Delegate
To start a thread, for Thread class we need to pass not a function but function pointer. delegate is the function pointer. when execute var t = new Thread(TimeConsumingWork); behind the seen program creates function pointer to TimeConsumingWork and pass to the Thread Class implicitly. but for more understand we can use ThreadStart delegate in deferent ways.
- var threadStartDelegate = new ThreadStart(TimeConsumingWork);
var thread = new Thread(threadStartDelegate); - var t = new Thread(() => TimeConsumingWork());
- var t = new Thread(delegate () { TimeConsumingWork(); });
ParameterizedThreadStart delegate
If need to pass some parameters to the method we can use parameterizedThreadStart delegate
Retrieving data from thread function
Thread Chaining
Task.Run(async () =>
{
await LongTaskAsync("A");
await LongTaskAsync("B");
await LongTaskAsync("C");
});
Thread.Join.
Block the current thread and wait untile all join threads are complete.Thread.Join has overrload method that specify the timeout.
without join
with join
with Join(timeout);
if timeout exceeded, main thread continue. but after particular thread will finish there work
===============================================================
Comparison
Without Concurrency or parallelism
With Async await 1
With Async Await 2
Using Threads/parallelism
No comments:
Post a Comment