从带有 ref 参数的方法调用 await 方法?

Call await method from a method with ref pameters?

我需要从 NavigateError 事件中调用一个 await 方法,我无法更改其签名(见下文):

void instance_NavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel);

将其标记为 async 所以我会这样做:

await myMethod(foo);

报错:

Error CS1988 Async methods cannot have ref or out parameters

我该如何解决这个问题?

无法使用 async/await 执行此操作。由于异步方法的工作方式,在异步方法中使用 ref/out 没有意义。

您没有指定 myMethod 的签名,因此下面的示例假定您需要异步方法的 return 值。如果你不需要等待方法完成,你可以像普通方法一样调用它:myMethod(foo)。请注意,myMethod 中抛出的任何异常都将被忽略。

解决方法是手动输入 .ContinueWith。因为这需要使用 lambda(或单独的方法),所以您将无法在此调用后设置 ref 参数。

private void instance_NavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel)
{
    myMethod(foo).ContinueWith(t => {
        var resultOfMethod = t.Result;

        // Do something with resultOfMethod
    });
}

您可以先将 ref 参数放在一个变量中来读取它们

private void instance_NavigateError(object pDisp, ref object URLref, ref object Frame, ref object StatusCode, ref bool Cancel)
{
    var URL = URLref;
    myMethod(foo).ContinueWith(t => {
        var resultOfMethod = t.Result;

        // Do something with resultOfMethod and URL
    });
}