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

时间:2018-10-21 20:04:49

标签: task-parallel-library

我创建了一个方法,该方法可以在启动作为参数传递的Task之前处理一些检查。

我的问题是,尽管代码仍在运行,但在那里创建的任务的行为不符合预期,并被迅速视为RanToCompletion。

这里是一个例子:

    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,但这似乎与我正确使用异步任务而不是异步void没什么问题。

此外,在我将代码执行移至AddToTasker方法内之前,该代码还可以正常运行。在我以前喜欢这样做AddToTasker(Task.Run(() => ExtractAllOffer(localToken), localToken), TaskTypes.Extractor);之前,但我意识到我需要在启动Task之前执行检查,并且需要在AddToTasker方法(我对此调用有很多次调用)中考虑这些检查。

我有点理解,我在声明或启动任务时存在缺陷,但无法弄清楚。

非常感谢帮助

1 个答案:

答案 0 :(得分:1)

感谢@ pere57以及其他thread,我看到等待只等到创建Task的操作完成...这是非常快的。

我必须将其声明为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 ***
}