SlideShare a Scribd company logo
1 of 57
Download to read offline
Binu Bhasuran
Microsoft MVP Visual C#
Facebook http://facebook.com/codeno47
Blog http://proxdev.com/
Threading model was introduced in which release of .NET framework?
1.0
1.1
2.0
3.5
3.5 SP1
2) Interlocked class introduced in which release of .NET framework?
2.0
4.0
3.5 SP1
4.5
1.1
3) Can you stop an Asynchronous delegate?
Yes
No
It depends on implementation.
It depends on .NET framework version.
4) By Default .NET application starts how many threads?
1
2
3
Depends on processor architecture.
Asynchronous operations are operations which are
initiated and then continue concurrently with the
invoking code.
When conforming to the .NET Task-Based Asynchronous
Pattern (TAP), asynchronous methods return a task that
represents the ongoing operation and allows waiting for
its eventual outcome.
Invoking and then asynchronously waiting for a task-
returning method to complete is as simple as “await
myAsyncMethod();”. The control flow is completely
unaltered, and there are no callbacks in sight because the
compiler takes care of creating and signing them up.
Convert synchronous code into asynchronous
code
Perform tasks without blocking the UI
Run concurrent tasks
Implement cancellation and polling features
Generate a DLL library that exposes
asynchronous methods
Initiation and completion of an asynchronous
operation in the TAP are represented by a single
method, and thus there is only one method to
name. This is in contrast to the IAsyncResult
pattern, or APM pattern, where BeginMethodName
and EndMethodName methods are required, and in
contrast to the event-based asynchronous pattern,
or EAP, where a MethodNameAsync is required in
addition to one or more events, event handler
delegate types, and EventArg-derived types.
Asynchronous methods in the TAP are named with
an “Async” suffix that follows the operation’s name,
e.g. MethodNameAsync.
The singular TAP method returns either a Task
or a Task<TResult>, based on whether the
corresponding synchronous method would
return void or a type TResult, respectively. (If
adding a TAP method to a class that already
contains a method MethodNameAsync, the
suffix “TaskAsync” may be used instead,
resulting in “MethodNameTaskAsync”.)
public class MyClass
{
public IAsyncResult BeginRead(
byte [] buffer, int offset, int count,
AsyncCallback callback, object state);
public int EndRead(IAsyncResult asyncResult);
}
public class MyClass
{
public void ReadAsync(byte [] buffer, int offset, int count);
public event ReadCompletedEventHandler ReadCompleted;
}
public delegate void ReadCompletedEventHandler(
object sender, ReadCompletedEventArgs eventArgs);
public class ReadCompletedEventArgs : AsyncCompletedEventArgs
{
public int Result { get; }
}
TAP counterpart would expose the following
single method:
public class MyClass
{
public Task<int> ReadAsync(byte [] buffer, int
offset, int count);
}
The parameters to a basic TAP method should be
the same parameters provided to the synchronous
counterpart, in the same order.
However, “out” and “ref” parameters are exempted
from this rule and should be avoided entirely.
Any data that would have been returned through
an out or ref parameter should instead be returned
as part of the returned Task<TResult>’s Result,
utilizing a tuple or a custom data structure in order
to accommodate multiple values.
To expose a cancelable asynchronous operation,
a TAP implementation provides an overload that
accepts a CancellationToken after the
synchronous counterpart method’s parameters.
By convention, the parameter should be named
“cancellationToken”.
public Task<int> ReadAsync(
byte [] buffer, int offset, int count,
CancellationToken cancellationToken);
If the token has cancellation requested and the
asynchronous operation is able to respect that
request, the returned task will end in the
TaskStatus.Canceled state; there will be no
available Result and no Exception
In the TAP, progress is handled through an IProgress<T> interface
passed into the asynchronous method as a parameter named
“progress”.
Providing the progress interface at the time of the asynchronous
method’s invocation helps to eliminate race conditions that result
from incorrect usage where event handlers incorrectly registered after
the invocation of the operation may miss updates.
More importantly, it enables varying implementations of progress to
be utilized, as determined by the consumer
public Task<int> ReadAsync(
byte [] buffer, int offset, int count,
IProgress<int> progress);
A single IProgress<T> implementation, Progress<T>, is
provided built-in (more implementations may be provided in
the future). The Progress<T> class is declared as follows:
public class Progress<T> : IProgress<in T>
{
public Progress();
public Progress(Action<T> handler);
protected OnReport(T value);
public event ProgressEventHandler<T> ProgressChanged;
}
public Task MethodNameAsync(…);
public Task MethodNameAsync(…, CancellationToken cancellationToken);
public Task MethodNameAsync(…, IProgress<T> progress);
public Task MethodNameAsync(…,
CancellationToken cancellationToken, IProgress<T> progress);
PatternsandTypes
From APM to Tasks
From Tasks to APM
Tasks and the Event-based Asynchronous
Pattern (EAP)
Tasks and WaitHandles
From Tasks to WaitHandles
The .NET Framework 1.0 saw the introduction of the
IAsyncResult pattern, otherwise known as the Asynchronous
Programming Model (APM) pattern, or the Begin/End
pattern.
The .NET Framework 2.0 then brought with it the event-based
asynchronous pattern (EAP).
The new TAP deprecates both of its predecessors, while at the
same time providing the ability to easily build migration
routines from the APM and EAP to TAP.
The APM pattern relies on two corresponding methods
to represent an asynchronous operation:
BeginMethodName and EndMethodName. At a high-
level, the begin method accepts as parameters to the
method the same parameters that would be supplied
to the MethodName synchronous method counterpart,
as well as also accepting an AsyncCallback delegate
and an object state
The begin method then returns an IAsyncResult, which
returns from its AsyncState property the object state
passed to the begin method. When the asynchronous
operation completes, the IAsyncResult’s IsCompleted
will start returning true, and its AsyncWaitHandle will
be set.
Additionally, if the AsyncCallback parameter to the begin
method was non-null, the callback will be invoked and passed
the same IAsyncResult that was returned from the begin
method.
When the asynchronous operation does complete, the
EndMethodName method is used to join with the operation,
retrieving any results or forcing any exceptions that occurred
to then propagate. There are further details around the
IAsyncResult’s CompletedSynchronously property that are
beyond the scope of this document; for more information,
see MSDN
Given the very structured nature of the APM pattern, it
is quite easy to build a wrapper for an APM
implementation to expose it as a TAP implementation.
In fact, the .NET Framework 4 includes helper routines
in the form of TaskFactory.FromAsync to provide this
translation.
Consider the .NET Stream class and its BeginRead/EndRead
methods, which represent the APM counterpart to the
synchronous Read method:
public int Read(
byte [] buffer, int offset, int count);
…
public IAsyncResult BeginRead(
byte [] buffer, int offset, int count,
AsyncCallback callback, object state);
public int EndRead(IAsyncResult asyncResult);
Utilizing FromAsync, we can implement a TAP wrapper for this method as follows:
public static Task<int> ReadAsync(
this Stream stream, byte [] buffer, int offset, int count)
{
if (stream == null) throw new ArgumentNullException(“stream”);
return Task<int>.Factory.FromAsync(stream.BeginRead,
stream.EndRead,
buffer, offset, count, null);
}
This implementation that utilizes FromAsync is effectively equivalent to the following:
public static Task<int> ReadAsync(
this Stream stream, byte [] buffer, int offset, int count)
{
if (stream == null) throw new ArgumentNullException(“stream”);
var tcs = new TaskCompletionSource<int>();
stream.BeginRead(buffer, offset, count, iar =>
{
try { tcs.TrySetResult(stream.EndRead(iar)); }
catch(OperationCanceledException) { tcs.TrySetCanceled(); }
catch(Exception exc) { tcs.TrySetException(exc); }
}, null);
return tcs.Task;
}
For cases where existing infrastructure expects code to
implement the APM pattern, it is also important to be
able to be able to take a TAP implementation and use it
where an APM implementation is expected.
public static IAsyncResult AsApm<T>(
this Task<T> task, AsyncCallback callback, object state)
{
if (task == null) throw new ArgumentNullException(“task”);
var tcs = new TaskCompletionSource<T>(state);
task.ContinueWith(t =>
{
if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions)
else if (t.IsCanceled) tcs.TrySetCanceled();
else tcs.TrySetResult(t.Result);
if (callback != null) callback(tcs.Task);
});
return tcs.Task;
}
Now, consider a case where we have a TAP implementation:
public static Task<string> DownloadStringAsync(Uri url);
And we need to provide an APM implementation:
public IAsyncResult BeginDownloadString(Uri url, AsyncCallback callback, object state);
public string EndDownloadString(IAsyncResult asyncResult);
This is achievable with the following code:
public IAsyncResult BeginDownloadString(
Uri url, AsyncCallback callback, object state)
{
return DownloadStringAsync(url).AsApm(callback, state);
}
public string EndDownloadString(IAsyncResult asyncResult)
{
return ((Task<string>)asyncResult).Result;
}
The event-based asynchronous pattern relies on an
instance MethodNameAsync method which returns void,
accepts the same parameters as the synchronous
MethodName method, and initiates the asynchronous
operation.
Prior to initiating the asynchronous operation, event
handlers are registered with events on the same instance,
and these events are then raised to provide progress and
completion notifications. The event handlers are typically
custom delegate types that utilize event argument types
that are or that are derived from
ProgressChangedEventArgs and AsyncCompletedEventArgs.
public static Task<string> DownloadStringAsync(Uri url)
{
var tcs = new TaskCompletionSource<string>();
var wc = new WebClient();
wc.DownloadStringCompleted += (s,e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
wc.DownloadStringAsync(url);
return tcs.Task;
}
While not an asynchronous pattern per-se,
advanced developers may find themselves
utilizing WaitHandles and the ThreadPool’s
RegisterWaitForSingleObject method to be
notified asynchronously when a WaitHandle is
set.
We can wrap RegisterWaitForSingleObject to
enable a task-based alternative to any
synchronous wait on a WaitHandle:
public static Task WaitOneAsync(this WaitHandle waitHandle)
{
if (waitHandle == null) throw new ArgumentNullException("waitHandle");
var tcs = new TaskCompletionSource<bool>();
var rwh = ThreadPool.RegisterWaitForSingleObject(waitHandle,
delegate { tcs.TrySetResult(true); }, null, -1, true);
var t = tcs.Task;
t.ContinueWith(_ => rwh.Unregister(null));
return t;
}
The Task class implements IAsyncResult, and its
IAsyncResult implementation exposes an
AsyncWaitHandle property which returns a WaitHandle
that will be set when the Task completes. As such,
getting a WaitHandle for a Task is accomplished as
follows:
WaitHandle wh =
((IAsyncResult)task).AsyncWaitHandle;
We will create a WPF application to download a
web page and find any link in the HTML. You will
write the code in the old way by using
synchronous calls and finally run the application
to see the disadvantages of this way of
programming
In this exercise, you will create a very simple application
that will download the HTML content of a web page and,
using regular expressions, search through that content
looking for any link. Then, you will display those links in a
ListBox. You will build this application in two ways. First,
you will build the application using synchronous code
and examine the issues with this implementation.
Second, you will modify that application to use the
asynchronous code so you can see how this
implementation addresses the issues with the first
version of the application.
try
{
var response = new HttpClient().Get("http://msdn.microsoft.com");
string result =
response.EnsureSuccessStatusCode().Content.ReadAsString();
this.textBox1.Text = result;
}
catch (Exception)
{
MessageBox.Show(ex.ToString());
}
Notice the window is unresponsive and the
button actually never disables because the UI is
blocked while it downloads the web page.
In the previous code, you are using the
asynchronous version of the Get method,
the GetAsync, which is a new method added by
the .NET Framework 4.5 and has different
signature since it returns aTask type object. A
task represents an asynchronous operation
which may complete at some point in the
future.
try
{
var response = new
HttpClient().GetAsync("http://msdn.microsoft.com");
string result =
response.EnsureSuccessStatusCode().Content.ReadAsStri
ng();
this.textBox1.Text = result;
...
Adding the await keyword tells the compiler to
asynchronously wait for the task returned from the
method call.
This means that the rest of the code will be executed as a
callback only after the awaited method completes.
Another thing to notice is that you do not need to
change your try-catch block in order to make this work,
as the exceptions that happen in the background or in
the foreground will still be caught without any extra work
using a handler provided by the framework.
try
{
var response = await new
HttpClient().GetAsync("http://msdn.microsoft.com");
string result =
response.EnsureSuccessStatusCode().Content.ReadAsStri
ng();
this.textBox1.Text = result;
The await operator is applied to a task in an asynchronous method to
suspend the execution of the method until the awaited task
completes. The task represents ongoing work.
The asynchronous method in which await is used must be modified by
the async keyword. Such a method, defined by using the async
modifier, and usually containing one or more await expressions, is
referred to as an async method.
The task to which the await operator is applied typically is the return
value from a call to a method that implements the Task-Based
Asynchronous Pattern. Examples include values of type Task or
Task<TResult>.
An await expression does not block the thread
on which it is executing. Instead, it causes the
compiler to sign up the rest of the async
method as a continuation on the awaited task.
Control then returns to the caller of the async
method. When the task completes, it invokes its
continuation, and execution of the async
method resumes where it left off.
An await expression does not block the thread on which it is executing.
Instead, it causes the compiler to sign up the rest of the async method as a
continuation on the awaited task. Control then returns to the caller of the
async method. When the task completes, it invokes its continuation, and
execution of the async method resumes where it left off.
An await expression can occur only in the body of an immediately enclosing
method, lambda expression, or anonymous method that is marked by an
async modifier. The term await serves as a contextual keyword only in that
context. Elsewhere, it is interpreted as an identifier. Within the method,
lambda expression, or anonymous method, an await expression cannot occur
in the body of a synchronous function, in a query expression, in the catch or
finally block of an exception handling statement, in the block of a lock
statement, or in an unsafe context.
private async void button1_Click(object sender, EventArgs e)
{
// Call the method that runs asynchronously.
string result = await WaitAsynchronouslyAsync();
// Call the method that runs synchronously.
//string result = await WaitSynchronously ();
// Display the result.
textBox1.Text += result;
}
// The following method runs asynchronously. The UI thread is not
// blocked during the delay. You can move or resize the Form1 window
// while Task.Delay is running.
public async Task<string> WaitAsynchronouslyAsync()
{
await Task.Delay(10000);
return "Finished";
}
// The following method runs synchronously, despite the use of async.
// You cannot move or resize the Form1 window while Thread.Sleep
// is running because the UI thread is blocked.
public async Task<string> WaitSynchronously()
{
// Add a using directive for System.Threading.
Thread.Sleep(10000);
return "Finished";
}
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 long-running 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.
Typically, a method modified by the async keyword
contains at least one await expression or statement. The
method runs synchronously until it reaches the
firstawait 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.
The async keyword is a contextual keyword. It is a
keyword when it modifies a method, a lambda
expression, or an anonymous method. In all other
contexts, it is interpreted as an identifier.
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 async method can have a return type of void, Task,
or Task<TResult>. The method cannot declare
any ref or out parameters, although it can call methods that
have such parameters.
The void return type is used primarily to define event
handlers, where a void return type is required. An async
method that returns void cannot be awaited.
In other cases, you specify Task<T> for the return type of an
async method if the return statement of the method specifies
an operand of type T. You use Task if no meaningful value is
returned when the method is completed. You can think of
the Task return type as meaning "Task<void>." That is, a call
to the method returns a Task, but when the Task is
completed, any await expression that is awaiting
the Task evaluates to void.
// 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 += "rnControl returned to button1_Click.rn";
}
// 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 += "rnControl returned to button1_Click.rn";
}
// 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();
}
Visual Studio 11 Developer Preview
http://msdn.microsoft.com/en-
us/vstudio/hh127353
http://msdn.microsoft.com/en-
us/library/hh156513(v=vs.110).aspx
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#

More Related Content

What's hot

Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the ServerDoug Jones
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
 
Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4Wei Sun
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctpPratik Khasnabis
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsAyush Sharma
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexAkshay Varu
 
OTP application (with gen server child) - simple example
OTP application (with gen server child) - simple exampleOTP application (with gen server child) - simple example
OTP application (with gen server child) - simple exampleYangJerng Hwa
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014Thomas Lockney
 
Inside asp.net mvc framework
Inside asp.net mvc frameworkInside asp.net mvc framework
Inside asp.net mvc frameworkCiklum Ukraine
 
Inside ASP.NET MVC framework
Inside ASP.NET MVC frameworkInside ASP.NET MVC framework
Inside ASP.NET MVC frameworkCiklum Ukraine
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerApache Traffic Server
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaMike Nakhimovich
 
Infrastructure & System Monitoring using Prometheus
Infrastructure & System Monitoring using PrometheusInfrastructure & System Monitoring using Prometheus
Infrastructure & System Monitoring using PrometheusMarco Pas
 
Reduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin CoroutinesReduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin CoroutinesLINE Corporation
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with RxjavaChristophe Marchal
 

What's hot (20)

Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the Server
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
Async/Await
Async/AwaitAsync/Await
Async/Await
 
Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4
 
Async/Await Best Practices
Async/Await Best PracticesAsync/Await Best Practices
Async/Await Best Practices
 
Async await
Async awaitAsync await
Async await
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
 
AMC Minor Technical Issues
AMC Minor Technical IssuesAMC Minor Technical Issues
AMC Minor Technical Issues
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable Apex
 
OTP application (with gen server child) - simple example
OTP application (with gen server child) - simple exampleOTP application (with gen server child) - simple example
OTP application (with gen server child) - simple example
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Inside asp.net mvc framework
Inside asp.net mvc frameworkInside asp.net mvc framework
Inside asp.net mvc framework
 
Inside ASP.NET MVC framework
Inside ASP.NET MVC frameworkInside ASP.NET MVC framework
Inside ASP.NET MVC framework
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
 
Infrastructure & System Monitoring using Prometheus
Infrastructure & System Monitoring using PrometheusInfrastructure & System Monitoring using Prometheus
Infrastructure & System Monitoring using Prometheus
 
Reduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin CoroutinesReduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin Coroutines
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
 

Viewers also liked

27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examplesQuang Suma
 
Advanced c#
Advanced c#Advanced c#
Advanced c#saranuru
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)Koen Metsu
 
Microsoft Managed Extensibility Framework
Microsoft Managed Extensibility FrameworkMicrosoft Managed Extensibility Framework
Microsoft Managed Extensibility FrameworkBinu Bhasuran
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLMohammad Shaker
 
Advanced C#. Part 2
Advanced C#. Part 2Advanced C#. Part 2
Advanced C#. Part 2eleksdev
 
Advanced C#. Part 1
Advanced C#. Part 1Advanced C#. Part 1
Advanced C#. Part 1eleksdev
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel ProgrammingAlex Moore
 
What’s new in Visual Studio 2012 & .NET 4.5
What’s new in Visual Studio 2012 & .NET 4.5What’s new in Visual Studio 2012 & .NET 4.5
What’s new in Visual Studio 2012 & .NET 4.5Robert MacLean
 
Patterns For Cloud Computing
Patterns For Cloud ComputingPatterns For Cloud Computing
Patterns For Cloud ComputingSimon Guest
 
Web Application Development Fundamentals
Web Application Development FundamentalsWeb Application Development Fundamentals
Web Application Development FundamentalsMohammed Makhlouf
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web ArchitectureChamnap Chhorn
 

Viewers also liked (17)

.Net 3.5
.Net 3.5.Net 3.5
.Net 3.5
 
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)
 
Microsoft Managed Extensibility Framework
Microsoft Managed Extensibility FrameworkMicrosoft Managed Extensibility Framework
Microsoft Managed Extensibility Framework
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XML
 
Advanced C#. Part 2
Advanced C#. Part 2Advanced C#. Part 2
Advanced C#. Part 2
 
Advanced C#. Part 1
Advanced C#. Part 1Advanced C#. Part 1
Advanced C#. Part 1
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming
 
Cloud Computing
Cloud ComputingCloud Computing
Cloud Computing
 
What’s new in Visual Studio 2012 & .NET 4.5
What’s new in Visual Studio 2012 & .NET 4.5What’s new in Visual Studio 2012 & .NET 4.5
What’s new in Visual Studio 2012 & .NET 4.5
 
Patterns For Cloud Computing
Patterns For Cloud ComputingPatterns For Cloud Computing
Patterns For Cloud Computing
 
Cloud Computing
Cloud ComputingCloud Computing
Cloud Computing
 
SOA Unit I
SOA Unit ISOA Unit I
SOA Unit I
 
Web Application Development Fundamentals
Web Application Development FundamentalsWeb Application Development Fundamentals
Web Application Development Fundamentals
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 

Similar to Asynchronous programming in .net 4.5 with c#

Sync with async
Sync with  asyncSync with  async
Sync with asyncprabathsl
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Rainer Stropek
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETEvolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETAliaksandr Famin
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel ProcessingRTigger
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍명신 김
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfEngmohammedAlzared
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Yoshifumi Kawai
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3DHIRAJ PRAVIN
 
maXbox Starter 36 Software Testing
maXbox Starter 36 Software TestingmaXbox Starter 36 Software Testing
maXbox Starter 36 Software TestingMax Kleiner
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundKarel Zikmund
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and ParallelizationDmitri Nesteruk
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel ZikmundKarel Zikmund
 

Similar to Asynchronous programming in .net 4.5 with c# (20)

Sync with async
Sync with  asyncSync with  async
Sync with async
 
Async pattern
Async patternAsync pattern
Async pattern
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETEvolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NET
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel Processing
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdf
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
 
maXbox Starter 36 Software Testing
maXbox Starter 36 Software TestingmaXbox Starter 36 Software Testing
maXbox Starter 36 Software Testing
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Oop object oriented programing topics
Oop object oriented programing topicsOop object oriented programing topics
Oop object oriented programing topics
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
 

More from Binu Bhasuran

Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast trackBinu Bhasuran
 
Microsoft Azure solutions - Whitepaper
Microsoft Azure solutions - WhitepaperMicrosoft Azure solutions - Whitepaper
Microsoft Azure solutions - WhitepaperBinu Bhasuran
 
Restful Services With WFC
Restful Services With WFCRestful Services With WFC
Restful Services With WFCBinu Bhasuran
 
.Net platform an understanding
.Net platform an understanding.Net platform an understanding
.Net platform an understandingBinu Bhasuran
 
Moving from webservices to wcf services
Moving from webservices to wcf servicesMoving from webservices to wcf services
Moving from webservices to wcf servicesBinu Bhasuran
 
Model view view model
Model view view modelModel view view model
Model view view modelBinu Bhasuran
 
Beginning with wcf service
Beginning with wcf serviceBeginning with wcf service
Beginning with wcf serviceBinu Bhasuran
 

More from Binu Bhasuran (12)

Asp.net web api
Asp.net web apiAsp.net web api
Asp.net web api
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast track
 
Microsoft Azure solutions - Whitepaper
Microsoft Azure solutions - WhitepaperMicrosoft Azure solutions - Whitepaper
Microsoft Azure solutions - Whitepaper
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Restful Services With WFC
Restful Services With WFCRestful Services With WFC
Restful Services With WFC
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Wcf development
Wcf developmentWcf development
Wcf development
 
.Net platform an understanding
.Net platform an understanding.Net platform an understanding
.Net platform an understanding
 
Biz talk
Biz talkBiz talk
Biz talk
 
Moving from webservices to wcf services
Moving from webservices to wcf servicesMoving from webservices to wcf services
Moving from webservices to wcf services
 
Model view view model
Model view view modelModel view view model
Model view view model
 
Beginning with wcf service
Beginning with wcf serviceBeginning with wcf service
Beginning with wcf service
 

Recently uploaded

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 

Recently uploaded (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 

Asynchronous programming in .net 4.5 with c#

  • 1. Binu Bhasuran Microsoft MVP Visual C# Facebook http://facebook.com/codeno47 Blog http://proxdev.com/
  • 2. Threading model was introduced in which release of .NET framework? 1.0 1.1 2.0 3.5 3.5 SP1 2) Interlocked class introduced in which release of .NET framework? 2.0 4.0 3.5 SP1 4.5 1.1 3) Can you stop an Asynchronous delegate? Yes No It depends on implementation. It depends on .NET framework version. 4) By Default .NET application starts how many threads? 1 2 3 Depends on processor architecture.
  • 3. Asynchronous operations are operations which are initiated and then continue concurrently with the invoking code. When conforming to the .NET Task-Based Asynchronous Pattern (TAP), asynchronous methods return a task that represents the ongoing operation and allows waiting for its eventual outcome. Invoking and then asynchronously waiting for a task- returning method to complete is as simple as “await myAsyncMethod();”. The control flow is completely unaltered, and there are no callbacks in sight because the compiler takes care of creating and signing them up.
  • 4. Convert synchronous code into asynchronous code Perform tasks without blocking the UI Run concurrent tasks Implement cancellation and polling features Generate a DLL library that exposes asynchronous methods
  • 5. Initiation and completion of an asynchronous operation in the TAP are represented by a single method, and thus there is only one method to name. This is in contrast to the IAsyncResult pattern, or APM pattern, where BeginMethodName and EndMethodName methods are required, and in contrast to the event-based asynchronous pattern, or EAP, where a MethodNameAsync is required in addition to one or more events, event handler delegate types, and EventArg-derived types. Asynchronous methods in the TAP are named with an “Async” suffix that follows the operation’s name, e.g. MethodNameAsync.
  • 6. The singular TAP method returns either a Task or a Task<TResult>, based on whether the corresponding synchronous method would return void or a type TResult, respectively. (If adding a TAP method to a class that already contains a method MethodNameAsync, the suffix “TaskAsync” may be used instead, resulting in “MethodNameTaskAsync”.)
  • 7. public class MyClass { public IAsyncResult BeginRead( byte [] buffer, int offset, int count, AsyncCallback callback, object state); public int EndRead(IAsyncResult asyncResult); }
  • 8. public class MyClass { public void ReadAsync(byte [] buffer, int offset, int count); public event ReadCompletedEventHandler ReadCompleted; } public delegate void ReadCompletedEventHandler( object sender, ReadCompletedEventArgs eventArgs); public class ReadCompletedEventArgs : AsyncCompletedEventArgs { public int Result { get; } }
  • 9. TAP counterpart would expose the following single method: public class MyClass { public Task<int> ReadAsync(byte [] buffer, int offset, int count); }
  • 10. The parameters to a basic TAP method should be the same parameters provided to the synchronous counterpart, in the same order. However, “out” and “ref” parameters are exempted from this rule and should be avoided entirely. Any data that would have been returned through an out or ref parameter should instead be returned as part of the returned Task<TResult>’s Result, utilizing a tuple or a custom data structure in order to accommodate multiple values.
  • 11. To expose a cancelable asynchronous operation, a TAP implementation provides an overload that accepts a CancellationToken after the synchronous counterpart method’s parameters. By convention, the parameter should be named “cancellationToken”.
  • 12. public Task<int> ReadAsync( byte [] buffer, int offset, int count, CancellationToken cancellationToken); If the token has cancellation requested and the asynchronous operation is able to respect that request, the returned task will end in the TaskStatus.Canceled state; there will be no available Result and no Exception
  • 13. In the TAP, progress is handled through an IProgress<T> interface passed into the asynchronous method as a parameter named “progress”. Providing the progress interface at the time of the asynchronous method’s invocation helps to eliminate race conditions that result from incorrect usage where event handlers incorrectly registered after the invocation of the operation may miss updates. More importantly, it enables varying implementations of progress to be utilized, as determined by the consumer
  • 14. public Task<int> ReadAsync( byte [] buffer, int offset, int count, IProgress<int> progress);
  • 15. A single IProgress<T> implementation, Progress<T>, is provided built-in (more implementations may be provided in the future). The Progress<T> class is declared as follows: public class Progress<T> : IProgress<in T> { public Progress(); public Progress(Action<T> handler); protected OnReport(T value); public event ProgressEventHandler<T> ProgressChanged; }
  • 16. public Task MethodNameAsync(…); public Task MethodNameAsync(…, CancellationToken cancellationToken); public Task MethodNameAsync(…, IProgress<T> progress); public Task MethodNameAsync(…, CancellationToken cancellationToken, IProgress<T> progress);
  • 17. PatternsandTypes From APM to Tasks From Tasks to APM Tasks and the Event-based Asynchronous Pattern (EAP) Tasks and WaitHandles From Tasks to WaitHandles
  • 18. The .NET Framework 1.0 saw the introduction of the IAsyncResult pattern, otherwise known as the Asynchronous Programming Model (APM) pattern, or the Begin/End pattern. The .NET Framework 2.0 then brought with it the event-based asynchronous pattern (EAP). The new TAP deprecates both of its predecessors, while at the same time providing the ability to easily build migration routines from the APM and EAP to TAP.
  • 19. The APM pattern relies on two corresponding methods to represent an asynchronous operation: BeginMethodName and EndMethodName. At a high- level, the begin method accepts as parameters to the method the same parameters that would be supplied to the MethodName synchronous method counterpart, as well as also accepting an AsyncCallback delegate and an object state
  • 20. The begin method then returns an IAsyncResult, which returns from its AsyncState property the object state passed to the begin method. When the asynchronous operation completes, the IAsyncResult’s IsCompleted will start returning true, and its AsyncWaitHandle will be set.
  • 21. Additionally, if the AsyncCallback parameter to the begin method was non-null, the callback will be invoked and passed the same IAsyncResult that was returned from the begin method. When the asynchronous operation does complete, the EndMethodName method is used to join with the operation, retrieving any results or forcing any exceptions that occurred to then propagate. There are further details around the IAsyncResult’s CompletedSynchronously property that are beyond the scope of this document; for more information, see MSDN
  • 22. Given the very structured nature of the APM pattern, it is quite easy to build a wrapper for an APM implementation to expose it as a TAP implementation. In fact, the .NET Framework 4 includes helper routines in the form of TaskFactory.FromAsync to provide this translation.
  • 23. Consider the .NET Stream class and its BeginRead/EndRead methods, which represent the APM counterpart to the synchronous Read method: public int Read( byte [] buffer, int offset, int count); … public IAsyncResult BeginRead( byte [] buffer, int offset, int count, AsyncCallback callback, object state); public int EndRead(IAsyncResult asyncResult);
  • 24. Utilizing FromAsync, we can implement a TAP wrapper for this method as follows: public static Task<int> ReadAsync( this Stream stream, byte [] buffer, int offset, int count) { if (stream == null) throw new ArgumentNullException(“stream”); return Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, offset, count, null); }
  • 25. This implementation that utilizes FromAsync is effectively equivalent to the following: public static Task<int> ReadAsync( this Stream stream, byte [] buffer, int offset, int count) { if (stream == null) throw new ArgumentNullException(“stream”); var tcs = new TaskCompletionSource<int>(); stream.BeginRead(buffer, offset, count, iar => { try { tcs.TrySetResult(stream.EndRead(iar)); } catch(OperationCanceledException) { tcs.TrySetCanceled(); } catch(Exception exc) { tcs.TrySetException(exc); } }, null); return tcs.Task; }
  • 26. For cases where existing infrastructure expects code to implement the APM pattern, it is also important to be able to be able to take a TAP implementation and use it where an APM implementation is expected.
  • 27. public static IAsyncResult AsApm<T>( this Task<T> task, AsyncCallback callback, object state) { if (task == null) throw new ArgumentNullException(“task”); var tcs = new TaskCompletionSource<T>(state); task.ContinueWith(t => { if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions) else if (t.IsCanceled) tcs.TrySetCanceled(); else tcs.TrySetResult(t.Result); if (callback != null) callback(tcs.Task); }); return tcs.Task; }
  • 28. Now, consider a case where we have a TAP implementation: public static Task<string> DownloadStringAsync(Uri url); And we need to provide an APM implementation: public IAsyncResult BeginDownloadString(Uri url, AsyncCallback callback, object state); public string EndDownloadString(IAsyncResult asyncResult);
  • 29. This is achievable with the following code: public IAsyncResult BeginDownloadString( Uri url, AsyncCallback callback, object state) { return DownloadStringAsync(url).AsApm(callback, state); } public string EndDownloadString(IAsyncResult asyncResult) { return ((Task<string>)asyncResult).Result; }
  • 30. The event-based asynchronous pattern relies on an instance MethodNameAsync method which returns void, accepts the same parameters as the synchronous MethodName method, and initiates the asynchronous operation. Prior to initiating the asynchronous operation, event handlers are registered with events on the same instance, and these events are then raised to provide progress and completion notifications. The event handlers are typically custom delegate types that utilize event argument types that are or that are derived from ProgressChangedEventArgs and AsyncCompletedEventArgs.
  • 31. public static Task<string> DownloadStringAsync(Uri url) { var tcs = new TaskCompletionSource<string>(); var wc = new WebClient(); wc.DownloadStringCompleted += (s,e) => { if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(e.Result); }; wc.DownloadStringAsync(url); return tcs.Task; }
  • 32. While not an asynchronous pattern per-se, advanced developers may find themselves utilizing WaitHandles and the ThreadPool’s RegisterWaitForSingleObject method to be notified asynchronously when a WaitHandle is set. We can wrap RegisterWaitForSingleObject to enable a task-based alternative to any synchronous wait on a WaitHandle:
  • 33. public static Task WaitOneAsync(this WaitHandle waitHandle) { if (waitHandle == null) throw new ArgumentNullException("waitHandle"); var tcs = new TaskCompletionSource<bool>(); var rwh = ThreadPool.RegisterWaitForSingleObject(waitHandle, delegate { tcs.TrySetResult(true); }, null, -1, true); var t = tcs.Task; t.ContinueWith(_ => rwh.Unregister(null)); return t; }
  • 34. The Task class implements IAsyncResult, and its IAsyncResult implementation exposes an AsyncWaitHandle property which returns a WaitHandle that will be set when the Task completes. As such, getting a WaitHandle for a Task is accomplished as follows: WaitHandle wh = ((IAsyncResult)task).AsyncWaitHandle;
  • 35. We will create a WPF application to download a web page and find any link in the HTML. You will write the code in the old way by using synchronous calls and finally run the application to see the disadvantages of this way of programming
  • 36. In this exercise, you will create a very simple application that will download the HTML content of a web page and, using regular expressions, search through that content looking for any link. Then, you will display those links in a ListBox. You will build this application in two ways. First, you will build the application using synchronous code and examine the issues with this implementation. Second, you will modify that application to use the asynchronous code so you can see how this implementation addresses the issues with the first version of the application.
  • 37. try { var response = new HttpClient().Get("http://msdn.microsoft.com"); string result = response.EnsureSuccessStatusCode().Content.ReadAsString(); this.textBox1.Text = result; } catch (Exception) { MessageBox.Show(ex.ToString()); }
  • 38. Notice the window is unresponsive and the button actually never disables because the UI is blocked while it downloads the web page.
  • 39. In the previous code, you are using the asynchronous version of the Get method, the GetAsync, which is a new method added by the .NET Framework 4.5 and has different signature since it returns aTask type object. A task represents an asynchronous operation which may complete at some point in the future.
  • 40. try { var response = new HttpClient().GetAsync("http://msdn.microsoft.com"); string result = response.EnsureSuccessStatusCode().Content.ReadAsStri ng(); this.textBox1.Text = result; ...
  • 41. Adding the await keyword tells the compiler to asynchronously wait for the task returned from the method call. This means that the rest of the code will be executed as a callback only after the awaited method completes. Another thing to notice is that you do not need to change your try-catch block in order to make this work, as the exceptions that happen in the background or in the foreground will still be caught without any extra work using a handler provided by the framework.
  • 42. try { var response = await new HttpClient().GetAsync("http://msdn.microsoft.com"); string result = response.EnsureSuccessStatusCode().Content.ReadAsStri ng(); this.textBox1.Text = result;
  • 43. The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work. The asynchronous method in which await is used must be modified by the async keyword. Such a method, defined by using the async modifier, and usually containing one or more await expressions, is referred to as an async method. The task to which the await operator is applied typically is the return value from a call to a method that implements the Task-Based Asynchronous Pattern. Examples include values of type Task or Task<TResult>.
  • 44. An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.
  • 45. An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off. An await expression can occur only in the body of an immediately enclosing method, lambda expression, or anonymous method that is marked by an async modifier. The term await serves as a contextual keyword only in that context. Elsewhere, it is interpreted as an identifier. Within the method, lambda expression, or anonymous method, an await expression cannot occur in the body of a synchronous function, in a query expression, in the catch or finally block of an exception handling statement, in the block of a lock statement, or in an unsafe context.
  • 46. private async void button1_Click(object sender, EventArgs e) { // Call the method that runs asynchronously. string result = await WaitAsynchronouslyAsync(); // Call the method that runs synchronously. //string result = await WaitSynchronously (); // Display the result. textBox1.Text += result; }
  • 47. // The following method runs asynchronously. The UI thread is not // blocked during the delay. You can move or resize the Form1 window // while Task.Delay is running. public async Task<string> WaitAsynchronouslyAsync() { await Task.Delay(10000); return "Finished"; } // The following method runs synchronously, despite the use of async. // You cannot move or resize the Form1 window while Thread.Sleep // is running because the UI thread is blocked. public async Task<string> WaitSynchronously() { // Add a using directive for System.Threading. Thread.Sleep(10000); return "Finished"; }
  • 48. 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 long-running 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.
  • 49. Typically, a method modified by the async keyword contains at least one await expression or statement. The method runs synchronously until it reaches the firstawait 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. The async keyword is a contextual keyword. It is a keyword when it modifies a method, a lambda expression, or an anonymous method. In all other contexts, it is interpreted as an identifier.
  • 50. 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; }
  • 51. An async method can have a return type of void, Task, or Task<TResult>. The method cannot declare any ref or out parameters, although it can call methods that have such parameters. The void return type is used primarily to define event handlers, where a void return type is required. An async method that returns void cannot be awaited. In other cases, you specify Task<T> for the return type of an async method if the return statement of the method specifies an operand of type T. You use Task if no meaningful value is returned when the method is completed. You can think of the Task return type as meaning "Task<void>." That is, a call to the method returns a Task, but when the Task is completed, any await expression that is awaiting the Task evaluates to void.
  • 52. // 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 += "rnControl returned to button1_Click.rn"; }
  • 53. // 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 += "rnControl returned to button1_Click.rn"; }
  • 54. // 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(); }
  • 55. Visual Studio 11 Developer Preview http://msdn.microsoft.com/en- us/vstudio/hh127353 http://msdn.microsoft.com/en- us/library/hh156513(v=vs.110).aspx