Task vs AsParallel ()

On page 33 of Stephen Tuub's book

http://www.microsoft.com/download/en/details.aspx?id=19222

There is a code

var pings = from addr in addrs.AsParallel().WithDegreeOfParallelism(16) select new Ping().Send(addr); foreach (var ping in pings) Console.WriteLine("{0}: {1}", ping.Status, ping.Address); 

and according to Stephen the best version

 var pings = (from addr in addrs select new Ping().SendTask(addr, null)).ToArray(); Task.WaitAll(pings); foreach (Task<PingReply> ping in pings) Console.WriteLine("{0}: {1}", ping.Result.Status, ping.Result.Address); 

Stephen says the second option is better because "Task abstraction can also be used to represent operations with I / O binding and without thread binding to the Process."

But is it not worth it to just use Threadpool (hence just use threads) anyway? So, are you actually linking a thread?

+6
source share
1 answer

Not all tasks are work performed in a thread. Almost any task returned from TaskCompletionSource is something "different." And if we dig deeper into the SendTask method, we find its SentTaskCore :

 private static Task<PingReply> SendTaskCore(Ping ping, object userToken, Action<TaskCompletionSource<PingReply>> sendAsync) { // Validate we're being used with a real smtpClient. The rest of the arg validation // will happen in the call to sendAsync. if (ping == null) throw new ArgumentNullException("ping"); // Create a TaskCompletionSource to represent the operation var tcs = new TaskCompletionSource<PingReply>(userToken); // Register a handler that will transfer completion results to the TCS Task PingCompletedEventHandler handler = null; handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Reply, () => ping.PingCompleted -= handler); ping.PingCompleted += handler; // Try to start the async operation. If starting it fails (due to parameter validation) // unregister the handler before allowing the exception to propagate. try { sendAsync(tcs); } catch(Exception exc) { ping.PingCompleted -= handler; tcs.TrySetException(exc); } // Return the task to represent the asynchronous operation return tcs.Task; } 

So, no, it does not block the stream - it uses asynchronization completion mechanisms to avoid thread binding.


From the docs on TaskCompletionSource :

Represents the producer side of a non-delegate task, providing access to the consumer side through the Tasks property.

So, as he says, he supports the Task , which is not connected with the delegate - it allows you to pass on the Task to someone, and then organize how this task will be completed when the completion includes something other than the execution of the delegate.

+4
source

Source: https://habr.com/ru/post/906470/


All Articles