Is there a way to tell which Tasks are currently running in Task Parallel Library?

前端 未结 3 1200
小鲜肉
小鲜肉 2020-12-19 14:16

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 infor

3条回答
  •  北海茫月
    2020-12-19 15:10

    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();
            }
        }
    };
    

提交回复
热议问题