如何判断一个任务是否由另一个任务启动



我需要找到一个线程是否是另一个线程的子线程。

下面是一个过于简单化的例子,说明我正在尝试做什么,但基本上我需要判断一个任务是否是另一个任务的子任务。

如果我有一个函数可以启动几个任务。。。

_task1 = FuncA();
_task2 = FuncA();

在该功能中,它启动另一项任务

public async Task FuncA()
{
// do something
await Task.Delay(500, CancellationToken.None).ConfigureAwait(false);
// then call the other function
await FuncB().ConfigureAwait(false);
}
public async Task FuncB()
{
// now check for the 'parent'
if( IsChildTask(_task1) ) // <--- something similar 
{
// child of first task
}
}

我知道当前的thread id会发生变化,(因为async/await(是否可以判断当前任务/上下文/线程是否是另一个线程的子线程?。

最简单的解决方案,只需告诉谁是调用者

private string task1Name = "task1";
private string task2Name = "task2";
_task1 = FuncA(task1Name );
_task2 = FuncA(task2Name );
public async Task FuncA(sting taskName)
{
// do something
await Task.Delay(500, CancellationToken.None).ConfigureAwait(false);
// then call the other function
await FuncB(taskName).ConfigureAwait(false);
}
public async Task FuncB(string parentName)
{
// now check for the 'parent'
if( parentName == task1Name ) // <--- something similar 
{
// child of first task
}
}

相关内容

最新更新