Ayende @ Rahien

My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:


+972 52-548-6969

, @ Q c

Posts: 18 | Comments: 79

filter by tags archive

When using the Task Parallel Library, Wait() is a BAD warning sign

time to read 4 min | 761 words

Take a look at the following code:

public static Task ParseAsync(IPartialDataAccess source, IPartialDataAccess seed, Stream output, IEnumerable<RdcNeed> needList)
    return Task.Factory.StartNew(() =>
        foreach (var item in needList)
            switch (item.BlockType)
                case RdcNeedType.Source:
                    source.CopyToAsync(output, Convert.ToInt64(item.FileOffset), Convert.ToInt64(item.BlockLength)).Wait();
                case RdcNeedType.Seed:
                    seed.CopyToAsync(output, Convert.ToInt64(item.FileOffset), Convert.ToInt64(item.BlockLength)).Wait();
                    throw new NotSupportedException();

Do you see the problem in here?

It is a result of a code review comment about improper use of async in a project. This resulted in a lot of Task showing up in the return methods, but not in any measurable improvement in the actual codebase use of asynchronicity.

The problem is that when you need to work with such things in C# 4.0, you have to do some annoying things to get the code to work properly. In particular, this method was modified to be:

public static Task ParseAsync(IPartialDataAccess source, IPartialDataAccess seed, Stream output, IList<RdcNeed> needList, int position = 0)
  if(position>= needList.Count)
        return new CompletedTask();
  var item = needList[position];
  Task task;
  switch (item.BlockType)
        case RdcNeedType.Source:
            task = source.CopyToAsync(output, Convert.ToInt64(item.FileOffset), Convert.ToInt64(item.BlockLength));
        case RdcNeedType.Seed:
            task = seed.CopyToAsync(output, Convert.ToInt64(item.FileOffset), Convert.ToInt64(item.BlockLength));
            throw new NotSupportedException();

  return task.ContinueWith(resultTask =>
        if (resultTask.Status == TaskStatus.Faulted)
            resultTask.Wait(); // throws
        return ParseAsync(source, seed, output, needList, position + 1);

This code is more complex, but it is actually making proper use of the TPL. We have changed the loop into a recursive function, so we can take advantage of ContinueWith to the next iteration of the loop.

And no, I can’t wait to get to C# 5.0 and have proper await work.



Write yourself a ForeachAsync combinator for such things. It takes away all the recursive nastiness.

Graeme Christie

Or just use an Enumerator to mimick co-routines ... that's about my favourite .NET hack, I'll almost be a bit sad when we have c#5 await and I won't need to use it anymore.

Graeme Christie

Or just use an Enumerator to mimick co-routines ... that's about my favourite .NET hack, I'll almost be a bit sad when we have c#5 await and I won't need to use it anymore.

Simon Hughes

If the needList is large, you may blow your stack memory. There must be a better way.


I think this article describes extension you need here. http://blogs.msdn.com/b/pfxteam/archive/2010/11/21/10094564.aspx

George B

How would one be able to test this code to insure that its all operating on a new thread and that it is indeed running fully asynch? I've just started to dive into tasks and have no way of knowing if what I am doing is having an effect. Is there something I can write out to the console?


@George you can use a tool like log4net, if you set the pattern up correctly it will tell you the thread id in the log message - the defaults usually have this in. It's generally a good idea to have some kind of logging in your production apps any way and log4net is pretty universal. There's also classes in the System.Threading namespace that will give you information about the current thread.


I'm not that familiar with TPL, what's wrong with the firt example that requires the verbosity/complexity of the second?


@Matt, rumors say that you can't use log4net for TPL, log4net is old deprecated and stopped at C# 2.0. Something in the way TPL handles the threads influence the way log4net works.

But I know that NLog is perfect for the job :)


@Matt: Using the TPL doesn't necessarily mean using different threads, you know.

@Matt the second: In the first example, you're actually running the code synchronously on a different thread instead of using the TPL's ContinueWith. ContinueWith will continue after the first task is finished, without having a thread whose sole purpose is to Wait() on another task.

@Ayende: At least this example was simple enough that you didn't need gotos...

James Manning

In case anyone runs across this post and doesn't already know about it, you can use the Async Targeting Pack to build .NET 4 / SL5 apps and use async/await.


Comment preview

Comments have been closed on this topic.


  1. Production postmortem: The industry at large - 9 hours from now
  2. The insidious cost of allocations - about one day from now
  3. Buffer allocation strategies: A possible solution - 4 days from now
  4. Buffer allocation strategies: Explaining the solution - 5 days from now
  5. Buffer allocation strategies: Bad usage patterns - 6 days from now

And 2 more posts are pending...

There are posts all the way to Sep 11, 2015


  1. Find the bug (5):
    20 Apr 2011 - Why do I get a Null Reference Exception?
  2. Production postmortem (10):
    01 Sep 2015 - The case of the lying configuration file
  3. What is new in RavenDB 3.5 (7):
    12 Aug 2015 - Monitoring support
  4. Career planning (6):
    24 Jul 2015 - The immortal choices aren't
View all series


Main feed Feed Stats
Comments feed   Comments Feed Stats