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(); CancellationToken ct = cnslTokSrc.Token;
tsk = Task.Factory.StartNew((str) => { Load((List<string>)str); }, Lst, ct);
tsk.ContinueWith((s) =>
{
if (!ct.IsCancellationRequested)
{
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(); 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)
{
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.