-
Notifications
You must be signed in to change notification settings - Fork 1
Async Await Task
DUONG Phu-Hiep edited this page Feb 14, 2017
·
9 revisions
to read: Avoid async void link 1, link 2
https://msdn.microsoft.com/en-us/library/hh873177(v=vs.110).aspx
-
if a method is purely compute-bound, it should be exposed only as a synchronous implementation. Let the user choice if he want to wrap it to another
Task.Run
(orTaskFactory.StartNew
for more fine grained-control). -
All method invole I/O should have an async implementation. the TAP (Task Async Pattern) is implemented
-
with help of the compiler: async await
- compilers perform the necessary transformations to implement the method asynchronously
- An asynchronous method should return either a
System.Threading.Tasks.Task
or aSystem.Threading.Tasks.Task<TResult>
object - In the case of the latter, the body of the function should return a
TResult
, and the compiler ensures that this result is made available through the resulting task object - any exceptions that go unhandled within the body of the method are marshaled to the output task and cause the resulting task to end in the
TaskStatus.Faulted
state - The exception is when an
OperationCanceledException
(or derived type) goes unhandled, in which case the resulting task ends in theTaskStatus.Canceled state
-
or manually with TaskCompletionSource
-
Perform the asynchronous operation, and when it completes, call the
SetResult
,SetException
, orSetCanceled
method, or theTry
version of one of these methods -
Example:
public static Task<int> ReadTask(this Stream stream, byte[] buffer, int offset, int count, object state) { var tcs = new TaskCompletionSource<int>(); stream.BeginRead(buffer, offset, count, ar => { try { tcs.SetResult(stream.EndRead(ar)); } catch (Exception exc) { tcs.SetException(exc); } }, state); return tcs.Task; }
-
-