有没有办法查看任务是否已经有了延续?

huangapple go评论66阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月10日 16:32:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76216401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定