-
Notifications
You must be signed in to change notification settings - Fork 1
Async Await Task
DUONG Phu-Hiep edited this page Jul 28, 2016
·
9 revisions
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
- 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; }
-