0% found this document useful (0 votes)
49 views15 pages

Asynchronous in Dotnet4.5

The document discusses asynchronous programming in .NET 4.5 using tasks and async/await. It provides examples of constructing and running tasks, converting synchronous methods to asynchronous methods using async/await, and performing asynchronous operations sequentially and in parallel using tasks and async/await. Key aspects covered include Task and Task<T> types, ContinueWith to specify continuation tasks, async/await syntax and structure, and benefits of task parallelism for scalable and programmatic control.

Uploaded by

Sandeep Chavan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
49 views15 pages

Asynchronous in Dotnet4.5

The document discusses asynchronous programming in .NET 4.5 using tasks and async/await. It provides examples of constructing and running tasks, converting synchronous methods to asynchronous methods using async/await, and performing asynchronous operations sequentially and in parallel using tasks and async/await. Key aspects covered include Task and Task<T> types, ContinueWith to specify continuation tasks, async/await syntax and structure, and benefits of task parallelism for scalable and programmatic control.

Uploaded by

Sandeep Chavan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 15

Asynchronous in DotNet4.

http://msdn.microsoft.com/en-US/vstudio/
async
http://www.microsoft.com/download/en/de
tails.aspx?displaylang=en&id=9983

Task & Task<T>

var t = Task.Factory.StartNew(() => DoAction());


The Task.ContinueWith method and Task<TResult>.ContinueWith
method let you specify a task to be started when the antecedent
task finishes.

http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=VS.110).aspx

Action<object> action = (object obj) =>


{
Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, obj.ToString(),
Thread.CurrentThread.ManagedThreadId);
};
// Construct an unstarted task
Task t1 = new Task(action, "alpha");
// Cosntruct a started task
Task t2 = Task.Factory.StartNew(action, "beta");
// Block the main thread to demonstate that t2 is executing
t2.Wait();
// Launch t1
t1.Start();
Console.WriteLine("t1 has been launched. (Main Thread={0})",
Thread.CurrentThread.ManagedThreadId);
// Wait for the task to finish. You may optionally provide a timeout interval or a cancellation token to
mitigate situations when the task takes too long to finish.
t1.Wait();
// Construct an unstarted task
Task t3 = new Task(action, "gamma");
// Run it synchronously
t3.RunSynchronously();
// Although the task was run synchrounously, it is a good practice to wait for it which observes for
// exceptions potentially thrown by that task.
t3.Wait();

async await
The async modifier indicates that the method, lambda expression, or
anonymous method that it modifies is asynchronous. Such methods
are referred to as async methods.
An async method provides a convenient way to do potentially longrunning work without blocking the caller's thread. The caller of an
async method can resume its work without waiting for the async
method to finish.
The following example shows the structure of an async method. By
convention, async method names end in "Async.
Typically, a method modified by the async keyword contains at least
one await expression or statement. The method runs synchronously
until it reaches the first await expression, at which point it is
suspended until the awaited task is complete. In the meantime, control
is returned to the caller of the method. If the method does not contain
an await expression or statement, then it executes synchronously. A
compiler warning alerts you to any async methods that do not
contain await.
http://msdn.microsoft.com/en-us/library/hh156513(v=VS.110).aspx

public async Task<int> ExampleMethodAsync()


{
// . . .
// At the await expression, execution in this method is suspended and,
// if AwaitedProcessAsync has not already finished, control returns
// to the caller of ExampleMethodAsync.
int exampleInt = await AwaitedProcessAsync();
// . . .
// The return statement completes the task. Any method that is
// awaiting ExampleMethodAsync can now get the integer result.
return exampleInt;
}

// An event handler must return void.


private async void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Clear();
// SumPageSizesAsync returns a Task.
await SumPageSizesAsync();
textBox1.Text += "\r\nControl returned to button1_Click.\r\n";
}
// The following async lambda expression creates an equivalent anonymous
// event handler.
button1.Click += async (sender, e) => {
textBox1.Clear();
// SumPageSizesAsync returns a Task.
await SumPageSizesAsync();
textBox1.Text += "\r\nControl returned to button1_Click.\r\n";
}

// The following async method returns a Task<T>.


private async Task<byte[]> GetByteArrayAsync(Uri currentURI)
{
// Declare an HttpClient object.

HttpClient client = new HttpClient();


// The GetAsync method returns a Task(Of T), where T is an HttpResponseMessage.

Task<HttpResponseMessage> httpRMTask = client.GetAsync(currentURI);


// Await httpRMTask evaluates to an HttpResponseMessage object.

HttpResponseMessage httpRM = await httpRMTask;


// The following line can replace the previous two assignment statements .

//HttpResponseMessage httpRM = await client.GetAsync(currentURI);


// Throw an exception if the HttpResponseMessage contains an error code.

httpRM.EnsureSuccessStatusCode();
// Use ReadAsByteArray to access the content of the resource as a byte array.

return httpRM.Content.ReadAsByteArray();
}

Task Parallelism
The Task Parallel Library (TPL), as its name implies, is based on the concept of the
task. The term task parallelism refers to one or more independent tasks running
concurrently. A task represents an asynchronous operation, and in some ways it
resembles the creation of a new thread or ThreadPool work item, but at a higher level of
abstraction. Tasks provide two primary benefits:

More efficient and more scalable use of system resources.


Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with
algorithms (like hill-climbing) that determine and adjust to the number of threads that
maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to
enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are
employed to provide load-balancing.

More programmatic control than is possible with a thread or work item.

Tasks and the framework built around them provide a rich set of APIs that support
waiting, cancellation, continuations, robust exception handling, detailed status, custom scheduling,
and more.

For both of these reasons, in the .NET Framework 4, tasks are the preferred API for
writing multi-threaded, asynchronous, and parallel code.

http://msdn.microsoft.com/en-us/library/dd537609(v=VS.110).aspx

The following changes are all that is required to convert


from a synchronous to an asynchronous method.
In the method signature, make the following three
changes:
Mark the method with the Async or async modifier.
Change the return value from Byte() or byte[] to Task(Of Byte())
or Task<byte[]>.
By convention, add the suffix "Async" to the method name.

In the body of the method, make the following two


changes:
Change the method that is called from the synchronous Get
method to the asynchronous GetAsync method.
Apply the Await or await operator to the result of the method call.

That's it. Those few steps complete the conversion.


http://msdn.microsoft.com/en-us/library/hh191443(v=VS.110).aspx

Async Samples
http://www.wischik.com/lu/AsyncSilverlight/
AsyncSamples.html

Performs a series of web requests in


sequence using await. The next request
will not be issued until the previous
request completes.

public void AsyncIntroSerialBefore()


{
var client = new WebClient();

C# 4.0

client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_1;
client.DownloadStringAsync(new Uri("http://www.weather.gov"));
}
void AsyncIntroSerialBefore_DownloadStringCompleted_1(object sender, DownloadStringCompletedEventArgs e)
{
WriteLinePageTitle(e.Result);
var client = new WebClient();
client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_2;
client.DownloadStringAsync(new Uri("http://www.weather.gov/climate/"));
}
void AsyncIntroSerialBefore_DownloadStringCompleted_2(object sender, DownloadStringCompletedEventArgs e)
{
WriteLinePageTitle(e.Result);
var client = new WebClient();
client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_3;
client.DownloadStringAsync(new Uri("http://www.weather.gov/rss/"));
}
void AsyncIntroSerialBefore_DownloadStringCompleted_3(object sender, DownloadStringCompletedEventArgs e)
{
WriteLinePageTitle(e.Result);
}

Async
public async void AsyncIntroSerial()
{
var client = new WebClient();
WriteLinePageTitle(await client.DownloadStringTaskAsync(new
Uri("http://www.weather.gov")));
WriteLinePageTitle(await client.DownloadStringTaskAsync(new
Uri("http://www.weather.gov/climate/")));
WriteLinePageTitle(await client.DownloadStringTaskAsync(new
Uri("http://www.weather.gov/rss/")));
}

Resources

http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-829T

You might also like