Click here to Skip to main content
15,883,777 members
Articles / Desktop Programming / WPF
Tip/Trick

Asynchronous Programming

Rate me:
Please Sign up or sign in to vote.
4.57/5 (8 votes)
12 Nov 2013CPOL3 min read 24K   508   16   3
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

Image 1

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.

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

C++
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 

Image 2

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.

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

Task Cancellation 

Image 3

Image 4

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.

C#
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;
                }
            }
        }
    }
}

Image 5

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)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionA Slight Modification May Be Helpful Pin
George Swan11-Nov-13 9:28
mveGeorge Swan11-Nov-13 9:28 
AnswerRe: A Slight Modification May Be Helpful Pin
John Brett12-Nov-13 5:23
John 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.