Skip to content
DUONG Phu-Hiep edited this page Jul 28, 2016 · 9 revisions

https://msdn.microsoft.com/en-us/library/hh873177(v=vs.110).aspx

Workload: Compute-bound Tasks or I/O-bound Tasks or Mixed

  • 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 (or TaskFactory.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, or SetCanceled method, or the Try 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;
        }