async programming with async task

9

Click here to load reader

Upload: pierce-taylor

Post on 16-Dec-2015

295 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Async Programming WITH ASYNC TASK

Async ProgrammingWITH ASYNC TASK

http://bit.ly/AsyncTask

Page 2: Async Programming WITH ASYNC TASK

Responsiveness• File operation - If system is busy with I/O, file operation is bound to be slower.

• Web services – web services by very nature are unpredictable. Similarly access other web resources might have the same issue.

oUse of async prevents system from blocking the UI thread. When the data is available, the rest of the operation can continue.

oAsync await mechanism gives the same benefits without additional overhead with other methods (async event or use of threads)

oAsync await code executes on the same thread and not on independent thread.

oUse Task.Run to move CPU intensive work to background thread.

Page 3: Async Programming WITH ASYNC TASK

Easy to useasync and await make .NET and WinRT API consumeable from within your code.

They make asynchronous code as easy to create and use as synchronous code

async methods

Method signature contains async keyword.

Method name ends with Async (though this is just a naming convention and not a requirement)

Contains Task<T> or Task or void return types

Contains at least one await expression.

Page 4: Async Programming WITH ASYNC TASK
Page 5: Async Programming WITH ASYNC TASK
Page 6: Async Programming WITH ASYNC TASK
Page 7: Async Programming WITH ASYNC TASK

So what really happened there ?• A method that is marked as async results in creation of an additional structure. This structure

implements IAsyncStateMachine

• The MoveNext method contains the implementation of the async method.

• As you can see async does not result in thread creation.

• The async code is executed on the same thread as the one that initiated it.

• This makes async task based code easy to write and consume as one does not deal with multiple threads and thread synchronisation issues etc.

• This also means that for CPU bound operations, one needs to do a bit more work.

Page 8: Async Programming WITH ASYNC TASK

Running async on different thread ?• Task.Run

• ThreadPool.RunAsync

• Both an awaitable task so one can wait for the async task running on another thread.

• What is the difference ?

• Task.Run is uses .NET async task mechanism and .NET ThreadPool.

• ThreadPool.RunAsync is a WinRT implementation. Unless you have a specific need, one should use Task.Run as it is tried and tested code.

Page 9: Async Programming WITH ASYNC TASK

What about Task.Wait ?• It’s a blocking call.

• If UI thread is executing the task, called Wait / WaitAny / WaitAll will kill the app.

• Should try and use non-blocking WhenAny / WhenAll

• Can be used when using non UI thread for task execution..

• Within Task.Run / ThreadPool.RunAsync