简体   繁体   English

给定一个Task实例,我可以告诉它是否已调用ContinueWith吗?

[英]given a Task instance, can I tell if ContinueWith has been called on it?

Given a Task instance, how can I tell if ContinueWith has been called on it? 给定一个Task实例,如何判断是否已调用ContinueWith I want to know if I'm the last task executing in a chain. 我想知道我是否是链中最后执行的任务。

Task task = Task.FromResult();
void SomeMethod(var x) {
   task = task.ContinueWith(previous => {
       if (task.ContinueWith is called) return;
       // do something with x...
   }
}

If you meant multiple continuations. 如果您要多次延续。 A possible solution may be like this. 可能的解决方案可能是这样的。

class Program
    {
        public class TaskState
        {
            public bool Ended { get; set; }
        }

        static void Main(string[] args)
        {
            var task = Task.FromResult("Stackoverflow");
            var state = new TaskState();
            task.ContinueWith((result, continuationState) =>
            {
                Console.WriteLine("in first");


            }, state).ContinueWith((result, continuationState) =>
            {
                if (!state.Ended)
                    Console.WriteLine("in second");
                state.Ended = true;

            }, state).ContinueWith((result, continuationState) =>
            {
                if (!state.Ended)
                    Console.WriteLine("in third");
                state.Ended = true;

            }, state);
            Console.ReadLine();
        }

    }

You can have a static variable (a dictionary object) declared on the parent and update it with unique keyvalues when your Tasks are triggered. 您可以在父对象上声明一个静态变量(字典对象),并在触发任务时使用唯一的键值对其进行更新。 You can monitor this static variable to see if all the other threads has completed the execution or not. 您可以监视此静态变量,以查看所有其他线程是否已完成执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM