通用等待-如何安排继续?

I'm having an object at hand that may either be a Task, a ValueTask or a ValueTask<T> (optimally I can support any type of awaitable). Regardless of the actual type, I want to schedule a continuation. Optimally the continuation can determine whether the original awaitable has completed successfully, faulted or has been canceled.

怎么做?

我的第一次尝试是:

var getAwaiterMethod = invocation.ReturnValue.GetType().GetMethod(nameof(Task.GetAwaiter));
var awaiter = (INotifyCompletion) getAwaiterMethod.Invoke(myAwaitableObject, new object[0]);
awaiter.OnCompleted(() => myContinuation);

但是,在那种情况下,继续无法告诉等待对象是成功完成,发生故障还是已取消。

有没有更好的办法?

评论
  • 大四喜
    大四喜 回复

    You can await a dynamic type:

    dynamic o = myAwaitableObject;
    await o;
    

    I'm not sure how well that would work with ValueTask<T>, though; I haven't tried that yet.