2. Why Async ?
Async allows programmer to avoid performance
bottlenecks and improve applications responsiveness.
Scenario :
Applications access the HTTP (Web ) inside the program
Access the web is slow and delayed
Total application will be wait
Sync With Async - PrabathSL
3. Sync With Async - PrabathSL
private void uploadImageCallbackHell()
{
bool BufferStatus = true;
var filePicker = new FilePicker();
var PickerTask = filePicker.PickImage();
PickerTask.ContinueWith((PickerReturn) =>
{
if (PickerTask.IsCanceled)
{
BufferStatus = false;
}
else
{
var Uploadtask = new Task<bool>(() =>
{
return sendUpdate(PickerReturn);
});
Uploadtask.ContinueWith((UploadReturnTask)()=>
{
BufferStatus = false;
});
}
}
);
}
4. With Async Application can continue with other works that
doesn’t depend on blocked resource until the blocked task
finished.
Sync With Async - PrabathSL
5. Async
Async programming available with Visual Studio 2012
and .NET framework 4.5 onwards
Runtime components support Async:
Web ( HttpClient / SyndicationClient )
File Access ( StorageFile / StreamWriter / XmlReader )
Images ( MediaCapture / BitMapEncoder and Decoder )
Sync With Async - PrabathSL
7. Tasks
Reasoning about Background operations
Task and Task<T>
Encapsulate units of works
State : Running , Finished , Cancelled
Result
Thrown Exceptions
Sync With Async - PrabathSL
8. Working With Tasks
Useful Operations
Wait : Task.WaitAny(t1,t2,t3)
Wait : Task.WaitAll(t1,t1,t3)
Chain : task1.ContinueWith(task2)
Wrap : Task.WhenAny(t1,t2,t3)
Wrap : Task.WhenAll(t1,t2,t3)
Sync With Async - PrabathSL
9. Async Support
Base Class Libraries (BCL)
All standard Async API’s from .NET BCL
Coverage is .NET 4.5 Complete for BCL
What is available on Async
Any API that take more than 50ms to run
Sync With Async - PrabathSL
10. Compiler is Amazing
async key word informs the compiler that this method need
to be handle with it self
await indicates a suspension point where callback need to
be generated
Continuations are generated after each suspension point
Exception handling with Try Catch
Remember async and await , then use Tasks
Sync With Async - PrabathSL
11. How to use Async ?
private async void ButtonDefinition()
{
Async modifier can be on ,
Methods
Lambdas
Anonymous methods
button.Click += async (sender, e) =>{
int number = await getNumberAsync();
Use Coding standards
Use Async Suffix | e.g. DownloadAsync
Return Task or Task<T> according to situation
void for only event handlers
Sync With Async - PrabathSL
};
Task<int> itemNumberTask = getNumberAsync();
int num = await itemNumberTask;
}
private async Task<int> getNumberAsync()
{
await Task.Delay(200);
return 10;
}
14. Advanced Tips
Working with interdependent Async Operations ??
Mutual exclusion
Shared flag
Sleep and Wakeup
Mutex
Semaphore
Sync With Async - PrabathSL
15. Advanced Tips
Task manages set of class
Task.WhenAll(Ienumerable<Task>)
Require all class to complete
Task.WhenAny(Ienumerable<Task>)
Require any one of task completed
private async Task BulkTaskOperationAsync()
Sync With Async - PrabathSL
{
var t1 = await Task.Factory.StartNew(() => getNumberAsync());
var t2 = await Task.Factory.StartNew(() => getNumberAsync());
Task.WaitAny(t1, t2);
}
17. Thank You
Blog : prabathsl.blogspot.com
Email : prabathsl@outlook.com
Fb/ Twitter : @mpmpeiris
Sync With Async - PrabathSL
Notes de l'éditeur
Desire to build responsive applications
With long running tasks
Use background thread
Need to have own handshake protocol to calling its done or not , ended up with everyone make their own notification sytems
Database access or file access
Network connection interference
Working with call backs (node js ) pass message to other end of the day it will become more difficult to program
Support .NET base class libraries . It means what you did with regular .NET and now Async is there
Task is something like this , It will contains all other properties except the result. State , exceptions etc.
All the errors that thrown win the task execution is thrown after await is done.
Say to wait until any one of these are finished
Task 2 starts just after task1 (once file download you can convert it into another format)
Task encapsulates those tasks and any of them are finished main task is finished (getting same data from multiple distributed Db’s )
You ca use sync or async. Decide that make application better
When await keyword hit compiler going to look at task that is waiting generate code to run that in thread and managed that and error handing
With Task<int> method its not gonna just ended the task and finish the job. You can read the Task.result property to get int result. But Tasktast<int> itself make query the integer type result in Task.result
It returning int, but signature is Task<int>. Compiler identifies the return value is int an in the execution flow it is I task and return it as Task.result at the await finished
Await cant use in Catch or finally