C# - Running code asynchronously in parallel : <p>I have a C# console app that I'm using for experimentation. I have some blocks of code that I know that I want to run 1) Asynchronously 2) in Parallel and 3) Run some shared cleanup code when each block finishes. </p>

<p>I need to run the blocks asynchronously because each one is calling a web service. I need to run each block in parallel for performance reasons and no block is dependent on the other. Finally, I have a significant amount of clean-up and logging code that I want to run when each block finishes. For that reason, this code is shared. </p>

<p>I'm getting stuck in how to do this. Thus far, I've looked the following C# concepts:</p>

<p>1) <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1?view=netframework-4.7.1" rel="nofollow noreferrer">Tasks</a> - Pros: Good at running code asynchronously Cons: a) I do not see a way to define a task and pass it to a shared method so that I can run my clean up code. b) I do not see a good way to pass parameters to a Task</p>

<p>2) <a href="https://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx" rel="nofollow noreferrer">Actions</a> - Pros: a) Can define code blocks inline i.e. <code>var myAction = (Action)(() =&gt; { });</code>. b) Can easily pass parameters to the <code>Action</code>. Cons: Doesn't seem to be a way to run actions asynchronously, thus b) Not sure I can run actions in parallel.</p>

<p>As I write this question, it's clear I'm missing something. At first glance, Tasks seem like the correct road to go down. However, I do feel stuck in the fact that</p>

<pre><code>public void RunTaskInParallel(Task task)
{
  var startTime = DateTime.UtcNow;

  // Execute task code

  var executionTime = DateTime.UtcNow.Subtract(startTime);
  // Log the execution time    

  // Execute Clean-up Code
}
</code></pre>

<p>How do I run a block of code, asynchronously, in parallel, in a way that allows me to execute some shared clean-up code when all is said and done? I feel like I'm always getting two-of-three requirements, but struggling to get all three.</p>

<p>Thank you for your help!</p>
