任务状态更改为 RanToCompletion 而静止 运行

Task status changed to RanToCompletion while stille running

我创建了一个方法,它在启动作为参数传递的任务之前处理一些检查。

我的问题是在那里创建的任务没有按预期运行,并且很快被视为 RanToCompletion,尽管代码仍然是 运行ning。

这是一个例子:

    public Task Main(CancellationToken localToken)
    {
        try
        {
            AddToTasker(new Task(async () => await ExtractAllOffer(localToken), localToken), TaskTypes.Extractor);

            //this allows to extract only the task for the given task type through the list created in AddToTasker, actual code is not necessary the returned array is correct
            Task.WaitAll(GetTasksArray(new TaskTypes[]{TaskTypes.Extractor}), localToken);

            IsRunning = false;
        }
    }

    public void AddToTasker(Task task, TaskTypes taskstype)
    {

        /*
         * Whatever code to perform few check before starting the task
         * among which referencing the task within a list which holds also the taskstype
         */


        task.Start();

    }

    async private Task ExtractAllOffer(CancellationToken localToken)
    {
        // *** Do very long Stuff ***
    }

ExtractAllOffer 方法是一个循环,其中 await 外部代码完成有片刻。在第一个 await 处,Task.WaiAll 终止并转到 IsRunning = false

我检查了这个 thread 但它似乎不是同一个问题,因为我正确使用了异步任务而不是 async void。

此外,在我将任务执行转移到 AddToTasker 方法之前,代码正确地使用了 运行。在我以前这样做之前 AddToTasker(Task.Run(() => ExtractAllOffer(localToken), localToken), TaskTypes.Extractor); 但我意识到我需要在启动任务之前执行检查并且需要在 AddToTasker 方法中考虑检查(我多次调用此方法)。

我有点理解我声明或启动我的任务的方式存在缺陷,但无法确定是什么。

非常感谢帮助

感谢@pere57 和另一个 我看到等待只等到创建任务的操作完成...这非常快。

我必须将其声明为 Task,以便解包第一个 Task(操作)以访问内部 Task(实际执行的方法)。

就是这样:

public Task Main(CancellationToken localToken)
{
    try
    {
        AddToTasker(new Task<Task>(() => ExtractAllOffer(localToken), localToken), TaskTypes.Extractor);

        //this allows to extract only the task for the given task type through the list created in AddToTasker, actual code is not necessary the returned array is correct
        Task.WaitAll(GetTasksArray(new TaskTypes[]{TaskTypes.Extractor}), localToken);

        IsRunning = false;
    }
}

public void AddToTasker(Task<Task> task, TaskTypes taskstype)
{

    /*
     * Whatever code to perform few check before starting the task
     * among which referencing the task within a list which holds also the taskstype
     */

    mylistoftask.Add(task.Unwrap()); //I have now to unwrap the task to add the inner one in my list
    task.Start();

}

async private Task ExtractAllOffer(CancellationToken localToken)
{
    // *** Do very long Stuff ***
}