gpt4 book ai didi

c# - Task.ContinueWith 不调用第二个任务(只有第一个正在运行)

转载 作者:行者123 更新时间:2023-11-30 22:02:30 25 4
gpt4 key购买 nike

我的应用程序允许用户从 UI 创建“任务”对象并设置它们的执行顺序。从那里,当用户单击“运行”时,所有任务(按顺序)都将发送到一个假设链接并运行它们的类。类如下:

public class MaintenanceTask
{
private CancellationTokenSource m_CancellationTokenSource;
private Task m_BatchTask;

public MaintenanceTask()
{
m_CancellationTokenSource = new CancellationTokenSource();
}

public void AddTaskIdent(TaskIdentBase ident)
{
Task newTask = ident.Create(m_CancellationTokenSource.Token);

if (m_BatchTask == null)
m_BatchTask = newTask;
else
m_BatchTask.ContinueWith(prev=>newTask);
}

public void Run()
{
if (m_BatchTask != null)
m_BatchTask.Start();
}
}

AddTaskIdent 正在接收一个知道如何创建任务对象的基类。我的问题是调用 Run() 会启动发送给类(class)的第一个任务。它运行它,直到它运行后没有其他任务完成。它只是在第一个任务完成后停止。

ContinueWith 机制是否遗漏了什么?

最佳答案

问题出在这一行:

m_BatchTask.ContinueWith(prev=>newTask);

我假设 newTaskident.Create 返回时没有启动。所以你应该:

if (m_BatchTask != null)
{
m_BatchTask = newTask;
//you'd like to have the m_lastTask field because next chaining operation
//should be on the last task, not the one you are starting
m_lastTask = newTask;
}
else
{
m_lastTask.ContinueWith(
prev =>
{
newTask.Start();
//doesn't matter to return newTask because in that case
//on second chaining already you will get Task<Task>
return (object)null;
});
m_lastTask = newTask;
}

关于c# - Task.ContinueWith 不调用第二个任务(只有第一个正在运行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26861500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com