Click here to Skip to main content
Click here to Skip to main content
Go to top

Asynchronous Programming

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

Introduction

.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.

Background

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);
        }
        else
        {
            if (MessageBox.Show("Operation Cancelled...!", 
                "Information", MessageBoxButton.OK, 
                MessageBoxImage.Information) == MessageBoxResult.OK)
            {
                cnslTokSrc.Dispose();       //  Disposing the CancellationTokenSource for next Initiation.
                IsCanceled = false;
            }
        }
        IsBusy = false;
        tsk.Dispose();
    });
}

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)
            {
                asyncDoWork.ReportProgress(L[i]);
                Thread.Sleep(1000);
                i++;
            }
            else
            {
                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.
                    cnslTokSrc.Cancel();
                    if (cnslTokSrc.IsCancellationRequested)
                    {
                        break;
                    }
                }
                else
                {
                    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.

License

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

Share

About the Author

John Pravin
Software Developer
India India
No Biography provided

Comments and Discussions

 
QuestionMessage Automatically Removed PinmemberMember 1039652312-Nov-13 2:50 
QuestionA Slight Modification May Be Helpful PinmemberGeorge Swan11-Nov-13 9:28 
AnswerRe: A Slight Modification May Be Helpful PinmemberJohn Brett12-Nov-13 5:23 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 12 Nov 2013
Article Copyright 2013 by John Pravin
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid