Book Image

Learning .NET High-performance Programming

By : Antonio Esposito
Book Image

Learning .NET High-performance Programming

By: Antonio Esposito

Overview of this book

Table of Contents (16 chapters)
Learning .NET High-performance Programming
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Task-based Asynchronous Pattern (TAP)


The Task-based Asynchronous Pattern (TAP) is the newly provided asynchronous programming framework born in .NET 4. TAP provides features of APM and EAP with an added signaling lock like an API that offers a lot of interesting new features.

Task creation

In .NET, this asynchronous job takes the name of a task. A task is also a class of the System.Threading.Tasks namespace. Here is a basic example:

var task = Task.Run(() =>
    {
        Thread.Sleep(3000);
        //returns a random integer
        return DateTime.Now.Millisecond;
    });

Console.Write("Starting data computation...");

//waiting the completation
while (task.Status != TaskStatus.RanToCompletion)
{
    Console.Write(".");
    Thread.Sleep(100);
}
Console.WriteLine(" OK");
Console.WriteLine("END");
Console.ReadLine();

The preceding example is similar to the first one shown about the APM. Although a lambda expression is used here to create an anonymous method implementation, it is the same...