英文:
Is there a way to see if a task already has a continuation?
问题
有没有办法找出任务是否已经有延续?我想要为现有任务添加一个延续,只有当任务还没有延续时,像这样:
void RequestUpdate()
{
if (_updateTask.IsCompleted)
{
_updateTask = TakeASnapshotOfTheCurrentStateAndUpdateAsync();
}
else
{
if (!_updateTask.IsCompletedSuccessfully){ // 如何检查这一点?
_updateTask.ContinueWith(_ => RequestUpdate());
}
}
}
或者是否有更好的编写这种逻辑的方式?
英文:
Is there a way to find out if a task already has a continuation? I would like to add a continuation to an existing task, only if the task does not yet have a continuation, like this:
void RequestUpdate()
{
if (_updateTask.IsCompleted)
{
_updateTask = TakeASnapshotOfTheCurrentStateAndUpdateAsync();
}
else
{
if (_updateTask.HasNoContinuation){ // how do I check for this?
_updateTask.ContinueWith(() => RequestUpdate())
}
}
}
Or is there a better way to write this kind of logic?
答案1
得分: 7
Technically, we can break into private affairs of the Task
class with the help of reflection and implement something like this:
using System.Reflection;
...
private static bool HasContinuation(Task task) {
if (task is null)
return false;
var result = typeof(Task)
.GetField("m_continuationObject", BindingFlags.NonPublic | BindingFlags.Instance)
?.GetValue(task);
return result is not null && result?.GetType() != typeof(object);
}
However, the code above is nothing but a quick (and dirty) patch; there's no guarantee that future versions of .NET will use the m_continuationObject
field.
英文:
Technically, we can break into private affairs of the Task
class with a help of reflection and implement something like this:
using System.Reflection;
...
private static bool HasContinuation(Task task) {
if (task is null)
return false;
var result = typeof(Task)
.GetField("m_continuationObject", BindingFlags.NonPublic | BindingFlags.Instance)
?.GetValue(task);
return result is not null && result?.GetType() != typeof(object);
}
However, the code above is nothing but a quick (and dirty) patch; there's no guarantee that future versions of .net will use m_continuationObject
field.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论