Professional Documents
Culture Documents
Synchronous programming
Asynchronus programming
That means when each task is triggered then the program waits unit it finishes before
starting the next one.
In Asynchronus execution, the program doesnt run all tasks in sequence.
That means it fires the tasks concurrently, and then waits for their end
So in simple words, When you execute something synchronously, you wait for it to finish
before moving on to another task. When you execute something asynchronously, you can
move on to another task before it finishes.
So now, the question is, If asynchronous execution takes less total time to finish than
synchronous execution, why would anybody choose synchronous execution?
You must synchronize tasks. for e.g. you run a task that must be executed after the
other three have finished. You will have to create a mechanism to wait for all tasks to
finish before launching the new task.
You must address concurrency issues. If you have a shared resource, like a list that
is written in one task and read in another, make sure that its kept in a known state.
There is no logical sequence anymore. The tasks can end at any time, and you dont
have control of which one finishes first.
It may stop the user interface (UI) thread. Typically, these programs have only one UI
thread, and when you use it as a blocking operation, you get the spinning wheel (and
not responding in the caption title) in your programnot the best experience for
your users.
What is a Thread?
A Thread is the smallest unit of code to which an operating system allocates CPU time.
In multithreading, a single process has multiple threads of execution.If the system has
multiple cpus then it can run in parallel.
Advantages of Multithreading or
Asynchronous Programming:
Lets look at below examples to understand it better.
1.You have a program that checks dozen websites to get pricing information for a product.
So in this case, if the program does everything in single thread:
Then the main program is blocked until the web search finishes.
But if you run the web interface and search in different threads then the program can remain
responsive even while the search is still running.
2. Multithreading can also simplify your code. for e.g. you have a program that periodically
checks a collection of websites for news and stock prices. You can write a program that
repeatedly loops through each of the site to check them one after another and that would be
complicated.Another approach would be to assign separate thread to each website and let
each thread run independently.Now each thread will focus only on one website.
PLINQ
Background worker
o This component executes code on a separate thread.It uses events to
communicate with main user interface thread.
Tasks
o The task class let you create and run threads.
Threads
o The Thread class gives you lower level access to threads.