jay's old blog

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

Taks – Basics, Continuation and Completion

We did read about threads till now. Threads are great. They allow you to do multiple things at the same time. It's overall great. However, threads have some drawbacks. For instance, they don’t return when they are done. Which means, they are good but as programmers we need more control don’t' we.  

That is where Tasks come into picture. If you don’t need a return value, then, you will notice that tasks are created and used just like threads. You can see stuff like Thread.Sleep and other Thread related methods all you want. They will here as well.  

Things get strange when you use Threads to work with getting a return value. For instance, check this out.  

            Task<int> t2 = Task.Run(() => 
                int hello = 0; 
                for (int i = 0; i < 10; i++) 
                    Console.WriteLine("value of {0}", i); 
                    //displaying the thread id 
                    Console.WriteLine("Current thread is {0}", Thread.CurrentThread.ManagedThreadId); 
                    hello = hello + 1; 
                return (hello); 

The task t2 will return the 'hello' variable once the loop is done and when the task wishes to return. You see the thread cannot do that. A thread cannot return.  

There is one small difference though. With a thread, you are looking at Join() method. Here, you use the Wait() method. They both do the same thing. Wait for the main thread to finish (or stop)  

If there is something that needs to be done after the task has completed, you use the ContinueWith(). Suppose you are using a thread to calculate some big number. Once that calculation is done, you would like to continue by doing something else entirely on the same thread. Then, you use this.  

Further, when you want to do something when the task actually completes, you use  TaskContinuationOptions.OnlyOnRanToCompletion. Just to add, a task returning does not mean it has completed. It simply means that it is returning a value. Task completion is when the task is done with its run.  

As always, find the code at our repo. See if you can play some jumpy disco music while coding. It will really kick in your brain into high gear. It sure does work on us, here at study nildana. Don’t put the music too loud though. Disturbing your neighbors (and attracting  unwanted attention) is the last thing you want. You see, you are tapping away building the next great thing. To them, all they is some girl or guy sitting in front of a computer doing literally nothing else. 

Comments are closed