4

I can't see a way to see which tasks are running. There is the Task.Current property, but what if there are multiple tasks running? Is there a way to get this kind of information?

Alternately, is there a built in way to get notified when a task starts or completes?

BlackWasp
  • 4,933
  • 2
  • 30
  • 42
Mike Two
  • 44,935
  • 9
  • 80
  • 96
  • Do you need to get it programmatically, or is this for debugging? If it's for debugging, are you aware of the new debug views available for tasks? – Jon Skeet Oct 11 '09 at 19:35
  • I would like to get at it programmatically. I have seen the new debug views and they are great stuff, but not what I need in this case. – Mike Two Oct 11 '09 at 19:36

3 Answers3

3

Hey Mike, there is no public way of accessing the list of pending tasks in TPL. The mechanism that makes it available for the debugger relies on the fact that all threads will be frozen at enumeration time, therefore it can't be used at runtime.

Yes, there's a built in way to get notified whan a task completes. Check out the Task.ContinueWith APIs. Basically this API creates a new task that will fired up when the target task completes.

I'm assuming you want to do some quick accounting / progress reporting based on this, if that's the case, I'd recommend that you call task.ContinueWith() with the TaskContinuationOptions.ExecuteSynchronously flag. When you specify that the continuation action will be run right there on the same thread when the target task finishes (if you don't specify this the continuation task is queued up like any other regular task).

Hope this helps.

Huseyin

HYildiz
  • 224
  • 3
  • 2
3

You can also get the currently running task (or a Task's parent) with reflection:

static public class Extensions
{
    public static Task Parent(this Task t)
    {
        FieldInfo info = typeof(Task).GetField("m_parent", 
            BindingFlags.NonPublic | BindingFlags.Instance);
        return info != null ? (Task)info.GetValue(t) : null;
    }
    public static Task Self
    {
        get
        {
            return Task.Factory.StartNew(
                () => { },
                CancellationToken.None,
                TaskCreationOptions.AttachedToParent,
                TaskScheduler.Default).Parent();
        }
    }
};
Glenn Slayden
  • 17,543
  • 3
  • 114
  • 108
2

You can create a TaskScheduler class deriving from the provided one. Within that class you have full control and can add logging either side of the execution. See for example: http://msdn.microsoft.com/en-us/library/ee789351.aspx

You'll also need to use a Taskfactory with an instance of your class as the scheduler.

Ian Mercer
  • 38,490
  • 8
  • 97
  • 133