How can I cancel Task.WhenAll?

Use TaskCompletionSource<T> to create a task for some asynchronous condition that does not already have an asynchronous API. Use CancellationToken.Register to hook the modern CancellationToken-based cancellation system into another cancellation system. Your solution just needs to combine these two. I have a CancellationToken.AsTask() extension method in my AsyncEx library, but you can write your own … Read more

What is the ValueTask equivalent of Task.CompletedTask?

All structs have a default constructor. The default constructor of ValueTask creates a completed ValueTask: var completedValueTask = new ValueTask(); Or alternatively: ValueTask completedValueTask = default; Update: The official documentation has been updated with the following note: An instance created with the parameterless constructor or by the default(ValueTask) syntax (a zero-initialized structure) represents a synchronously, … Read more

When to cache Tasks?

I have trouble understanding how this actually helps more than just storing the results. When a method is marked with the async modifier, the compiler will automatically transform the underlying method into a state-machine, as Stephan demonstrates in previous slides. This means that the use of the first method will always trigger a creation of … Read more

what is the correct way to cancel multiple tasks in c#

Yeah, what you said about using a single CancellationToken is correct. You can create a single CancellationTokenSource and use its CancellationToken for all of the tasks. Your tasks should check the token regularly for cancellation. For example: const int NUM_TASKS = 4; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; Task[] tasks = new … Read more

Is it possible for a Dictionary in .Net to cause dead lock when reading and writing to it in parallel?

So your code is executing Dictionary.FindEntry. It’s not a deadlock – a deadlock happens when two threads block in a way which makes them wait for one another to release a resource, but in your case you’re getting two seemingly infinite loops. The threads aren’t locked. Let’s take a look at this method in the … Read more

Using Tasks with conditional continuations

I think your main problem is that you’re telling those two tasks to “Wait” with your call to Task.WaitAll(onSuccess, onError); The onSuccess and onError continuations are automatically setup for you and will be executed after their antecedent task completes. If you simply replace your Task.WaitAll(…) with taskThrows.Start(); I believe you will get the desired output. … Read more

What is the correct way to cancel an async operation that doesn’t accept a CancellationToken?

Assuming that you don’t want to call the Stop method on the TcpListener class, there’s no perfect solution here. If you’re alright with being notified when the operation doesn’t complete within a certain time frame, but allowing the original operation to complete, then you can create an extension method, like so: public static async Task<T> … Read more

.NET’s Multi-threading vs Multi-processing: Awful Parallel.ForEach Performance

Parallel.For doesn’t divide the input into n pieces (where n is the MaxDegreeOfParallelism); instead it creates many small batches and makes sure that at most n are being processed concurrently. (This is so that if one batch takes a very long time to process, Parallel.For can still be running work on other threads. See Parallelism … Read more

How to make Task.WaitAll() to break if any exception happened?

The following should do it without altering the code of the original tasks (untested): static bool WaitAll(Task[] tasks, int timeout, CancellationToken token) { var cts = CancellationTokenSource.CreateLinkedTokenSource(token); var proxyTasks = tasks.Select(task => task.ContinueWith(t => { if (t.IsFaulted) cts.Cancel(); return t; }, cts.Token, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current).Unwrap()); return Task.WaitAll(proxyTasks.ToArray(), timeout, cts.Token); } Note it only tracks faulted tasks … Read more

Sequential processing of asynchronous tasks

Here’s how it would work with async: try { await FooAsync(); await BarAsync(); await FubarAsync(); Console.WriteLine(“All done”); } catch(Exception e) // For illustration purposes only. Catch specific exceptions! { Console.WriteLine(e); } This would work on .NET 4.0 if you installed the (prerelease) Microsoft.Bcl.Async package. Since you’re stuck on VS2010, you can use a variant of … Read more