簡體   English   中英

給定一個Task實例,我可以告訴它是否已調用ContinueWith嗎?

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

給定一個Task實例,如何判斷是否已調用ContinueWith 我想知道我是否是鏈中最后執行的任務。

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

如果您要多次延續。 可能的解決方案可能是這樣的。

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

    }

您可以在父對象上聲明一個靜態變量(字典對象),並在觸發任務時使用唯一的鍵值對其進行更新。 您可以監視此靜態變量,以查看所有其他線程是否已完成執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM