Note that there are some explanatory texts on larger screens.

plurals
  1. POExpose a cancellable Task
    text
    copied!<p>I'm designing an API that exposes a cancellable <code>Task</code>, and want to make sure I have designed it correctly. Is there a standard pattern for exposing <code>Task</code>s (maybe something similar to the APM BeginXxx/EndXxx pattern)? Any suggestions to improve? See <code>MyAPI.Run</code></p> <p>Does <code>Test2</code> demonstrate the best way to run many <code>MyAPI.Run</code> tasks in parallel?</p> <pre><code>public static class MyAPI { public static Task&lt;MyResult&gt; Run( CancellationToken token ) { // lazily create Task, so as to include the specified CancellationToken return new Task&lt;MyResult&gt;( MyPrivateAsyncMethod, token, token ); } private static MyResult MyPrivateAsyncMethod( object state ) { CancellationToken ct = (CancellationToken)state; ct.ThrowIfCancellationRequested(); return new MyResult(); } } public static class TestMyAPI { // User can start the Task directly public static void Test1() { CancellationTokenSource cts = new CancellationTokenSource(); MyAPI.Run( cts.Token ) .ContinueWith( task =&gt; Console.WriteLine( task.Result.ToString() ) ) .Start(); } // User must wrap in new Tasks to get Parent/Child relationship public static void Test2() { CancellationTokenSource cts = new CancellationTokenSource(); Task.Factory.StartNew( () =&gt; { var childTasks = new[] { Task.Factory.StartNew&lt;MyResult&gt;( () =&gt; MyAPI.Run( cts.Token ).Result, cts.Token, TaskCreationOptions.AttachedToParent, TaskScheduler.Default ), Task.Factory.StartNew&lt;MyResult&gt;( () =&gt; MyAPI.Run( cts.Token ).Result, cts.Token, TaskCreationOptions.AttachedToParent, TaskScheduler.Default ) }; Task.Factory .ContinueWhenAll&lt;MyResult&gt;( childTasks, tasks =&gt; { foreach( var task in tasks ) task.ToString(); } ) .Start(); }, cts.Token ); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload