jay's old blog

this blog will be deleted soon - please visit my new blog - https://thesanguinetechtrainer.com

Threads and Tasks Revisited - Update 1

I have already written about threads and tasks here, here, here, here, here and here. I thought, perhaps it is time to revisit those topics.

Tasks and threads in c sharp are interconnecting concepts. Both allow you to build an application that can mimic the behavior of a multi threaded application. The idea behind any multitasking application is the same. There is just too much power at disposal and by switching them fast, you are able to give the impression that many things are happening at the same time. Perhaps the best example would be when you are driving. Obviously, your eye is on the road, but your hands are on the wheel, your legs on the breaks. While driving, you are able to glance at the speed, fuel level, and so on, all without ever stopping the  vehicle itself. You are doing many things at once, however they are not happening in a parallel fashion. Your attention does go from the road to the speed dial and come back, fast.

Same things happen in applications. Most computers today have super fast processors. It is possible to ask these processors to work with multiple 'thread' and make them do many things at a given unit of time, like per minute or per hour or per day. That is where threads and tasks come into the picture.

The primary difference between threads and tasks is the amount of control you have. With a thread, you simply assign stuff to another thread, and that's pretty much it. Threads do not return stuff, which make it 'not so easy' to use them when you are trying to make things happen after something has happened. You could say, a thread is like a one way street. Stuff goes away from you, but nothing comes back. With tasks, you have an option to keep track of things.

You use threads when you dont want to have extra control over the multi threading you are attempting to do. You use tasks when you want that extra control. Almost in all real life situations, you will end up tasks and threads. Also, when using tasks, you end up using a lot of lambda expressions as well.

As always, find the code at my bit bucket repo right here.

Follow me on twitter, facebook and instagram for more updates. Thanks!
Comments are closed