When should TaskCompletionSource be used?

I mostly use it when only an event based API is available (for example Windows Phone 8 sockets): public Task<Args> SomeApiWrapper() { TaskCompletionSource<Args> tcs = new TaskCompletionSource<Args>(); var obj = new SomeApi(); // will get raised, when the work is done obj.Done += (args) => { // this will notify the caller // of the … Read more

Parallel foreach with asynchronous lambda

If you just want simple parallelism, you can do this: var bag = new ConcurrentBag<object>(); var tasks = myCollection.Select(async item => { // some pre stuff var response = await GetData(item); bag.Add(response); // some post stuff }); await Task.WhenAll(tasks); var count = bag.Count; If you need something more complex, check out Stephen Toub’s ForEachAsync post.

Parallel.ForEach vs Task.Factory.StartNew

The first is a much better option. Parallel.ForEach, internally, uses a Partitioner<T> to distribute your collection into work items. It will not do one task per item, but rather batch this to lower the overhead involved. The second option will schedule a single Task per item in your collection. While the results will be (nearly) … Read more

What is the difference between Task.Run() and Task.Factory.StartNew()

The second method, Task.Run, has been introduced in a later version of the .NET framework (in .NET 4.5). However, the first method, Task.Factory.StartNew, gives you the opportunity to define a lot of useful things about the thread you want to create, while Task.Run doesn’t provide this. For instance, lets say that you want to create … Read more

Running multiple async tasks and waiting for them all to complete

Both answers didn’t mention the awaitable Task.WhenAll: var task1 = DoWorkAsync(); var task2 = DoMoreWorkAsync(); await Task.WhenAll(task1, task2); The main difference between Task.WaitAll and Task.WhenAll is that the former will block (similar to using Wait on a single task) while the latter will not and can be awaited, yielding control back to the caller until … Read more

Awaiting multiple Tasks with different results

After you use WhenAll, you can pull the results out individually with await: var catTask = FeedCat(); var houseTask = SellHouse(); var carTask = BuyCar(); await Task.WhenAll(catTask, houseTask, carTask); var cat = await catTask; var house = await houseTask; var car = await carTask; You can also use Task.Result (since you know by this point … Read more

Synchronously waiting for an async operation, and why does Wait() freeze the program here

The await inside your asynchronous method is trying to come back to the UI thread. Since the UI thread is busy waiting for the entire task to complete, you have a deadlock. Moving the async call to Task.Run() solves the issue. Because the async call is now running on a thread pool thread, it doesn’t … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)