Click here to Skip to main content
13,148,136 members (36,138 online)
Click here to Skip to main content
Add your own
alternative version


16 bookmarked
Posted 11 Nov 2013

Asynchronous Programming

, 12 Nov 2013
Rate this:
Please Sign up or sign in to vote.
Asynchronous Programming with Task Parallel Library.


.Net Framework 4.0 introduces the Task Parallel Library (TPL). This library enhances multithreaded programming in two important ways. First, it simplifies the creation and use of multiple threads. Second, it automatically makes use of multiple processors. In other words, by using the TPL you enable your applications to automatically scale to make use of the number of available processors. By using Task objects, you can simplify the code and take advantage of the following useful functionality:

  • Register callbacks, in the form of task continuations, at any time after the task has started.
  • Coordinate multiple operations that execute in response to a Begin_ method, by using the ContinueWith() method.
  • Encapsulate asynchronous I/O-bound and compute-bound operations in the same Task object.
  • Monitor the status of the Task object.


Here I gave some trick that how to get access over the working process, which runs asynchronously in TPL. Task invocation, Task Pausing the operation, Task Cancellation. At the core of the TPL is the Task class. With the TPL, the basic unit of execution is encapsulated by Task, not Thread. Task differs from Thread in that Task is an abstraction that represents an asynchronous operation. Thread encapsulates a thread of execution. The Task class (and all of the TPL) is defined in System.Threading.Tasks.

Creating Task

Creating a Task for asynchronous operation. First we must implement the Namespace called System.Threading.Tasks for using the TPL. First create an object for Task and CancellationTokenSource as null_ outside the method, And instantiate the Task object and CancellationToken object inside a Method.

Task tsk = null;
CancellationTokenSource cnslTokSrc = null;   

Task object is initiated to start the asynchronous process where as cancellationTokenSource object is assigned to CancellationToken object. And the Task.Factory.StartNew() method is to create a task and start its execution in a single step by calling the StartNew( ) method defined by TaskFactory. TaskFactory is a class that provides various methods that streamline the creation and management of tasks. The default TaskFactory can be obtained from the read-only Factory property provided by Task. Using this property, you can call any of the TaskFactory methods. StartNew( ) automatically creates a Task instance for action and then starts the task by scheduling it for execution. Thus, there is no need to call Start( ) to invoke the Operation Task.

void LoadSrc()
	cnslTokSrc = new CancellationTokenSource();     //  Instantiating the cancellationTokenSource.
	//  Assign cancellationTokenSource object token to CancellationToken object.
    CancellationToken ct = cnslTokSrc.Token;
    //  Parameterized Action delegate using Lambda Expression with anonymous method.
    // The Object State is passed to the action delegate parameter and set to the method(typeCasted) to be invoked.
    tsk = Task.Factory.StartNew((str) => { Load((List<string>)str); }, Lst, ct);
    tsk.ContinueWith((s) =>
    //  It is the callBack method Invoked when the task completed.
    	if (!ct.IsCancellationRequested)
    	//  If the cancellationTokenSource is set to be canceled the IsCancellationRequest
    	// is set to be True. The Only thing is to identify that the task
    	// is completed with Cancellation Or Successfull.
            MessageBox.Show("Operation Completed Successfully...!", 
              "Information", MessageBoxButton.OK, MessageBoxImage.Information);
            if (MessageBox.Show("Operation Cancelled...!", 
                "Information", MessageBoxButton.OK, 
                MessageBoxImage.Information) == MessageBoxResult.OK)
                cnslTokSrc.Dispose();       //  Disposing the CancellationTokenSource for next Initiation.
                IsCanceled = false;
        IsBusy = false;

Task Continuation 

The TPL has the feature called ContinuWith() method. This method is acts as a callBack method, that enables you to call any method to be invoked at any time as you wish or else after the completion of the Task.

tsk.ContinueWith((s) =>{}); 

Task Cancellation 

CancellationToken classes support cancellation through the use of cancellation tokens. An object creates a cancellation token by using a CancellationTokenSource, and then passes the cancellation token to any number of threads or objects that should receive notice of cancellation. The token cannot be used to initiate cancellation. When the owning object calls Cancel on the CancellationTokenSource, the IsCancellationRequested property on every copy of the cancellation token is set to true.

void Load(List<string> L)
    int i = 0;
    while (i < L.Count)
        if (IsPaused != true)
            if (IsCanceled != true)
                if (MessageBox.Show("Do You Want To Cancel The Process...?", 
                    "Question", MessageBoxButton.YesNo, 
                    MessageBoxImage.Question) == MessageBoxResult.Yes)
                    //  If the owning object calls Cancel on the
                    //  CancellationTokenSource, the IsCancellationRequested
                    //  property on every copy of the cancellation token is set to true.
                    if (cnslTokSrc.IsCancellationRequested)
                    IsCanceled = false;

Points of Interest

Even Though the TPL is much advanced it is somewhat like the Legacy code but the Difference is TPL is quiet easy than the Legacy code, by invoking the process in a single line. But Not knowing of Legacy code, TPL is Complicated.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

John Pravin
Software Developer
India India
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionMessage Closed Pin
12-Nov-13 2:50
memberMember 1039652312-Nov-13 2:50 
QuestionA Slight Modification May Be Helpful Pin
George Swan11-Nov-13 9:28
memberGeorge Swan11-Nov-13 9:28 
AnswerRe: A Slight Modification May Be Helpful Pin
John Brett12-Nov-13 5:23
memberJohn Brett12-Nov-13 5:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170924.1 | Last Updated 12 Nov 2013
Article Copyright 2013 by John Pravin
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid