C# AsyncWaitHandle终止第三方API是否正确实现?

C# AsyncWaitHandle终止第三方API是否正确实现?,c#,delegates,iasyncresult,C#,Delegates,Iasyncresult,“session.identify”是我调用的第三方COM API,没有访问权限。它执行一个服务器查询,有时会被锁定(从而停止等待结果的主程序) 我的尝试是将它包装在一个AsyncDelegate中,这样我就能够给它一个超时,并且在超时过期后允许主程序继续运行(类似于,只需要返回一个值)。但是,它仍然会锁定,而超时不起作用 我是否错误地使用了AsyncHandle.WaitOne?API中是否存在阻止其中止的内容 private delegate void AsyncIdentifyCaller

“session.identify”是我调用的第三方COM API,没有访问权限。它执行一个服务器查询,有时会被锁定(从而停止等待结果的主程序)

我的尝试是将它包装在一个AsyncDelegate中,这样我就能够给它一个超时,并且在超时过期后允许主程序继续运行(类似于,只需要返回一个值)。但是,它仍然会锁定,而超时不起作用

我是否错误地使用了AsyncHandle.WaitOne?API中是否存在阻止其中止的内容

private delegate void AsyncIdentifyCaller(CoAudioIdSignature signature, uint numResults, uint serverFlags , out IIdentifyResult result);

private IIdentifyResult identifyAndWait(CoAudioIdSession session, CoAudioIdSignature signature, uint numResults, out IIdentifyResult iresult)
{
    AsyncIdentifyCaller identifyDelegate = new AsyncIdentifyCaller(session.Identify);

    IAsyncResult result = identifyDelegate.BeginInvoke(
        signature,
        numResults,
        0,
        out iresult,
        null,
        null);

    // wait up to timeout [ms] and then continue without a proper result 
    int timeout = 30000;
    result.AsyncWaitHandle.WaitOne(timeout, false);

    identifyDelegate.EndInvoke(out iresult, result);

    return iresult;
}

从我的理解来看,您应该对WaitOne()方法的返回值进行逻辑检查,并将您的逻辑封装在该值周围

无论是否发生超时,您都在运行EndInvoke,因此您从session.Identify获得相同的超时错误

result.AsyncWaitHandle.WaitOne(timeout, false); // checks if theres is a timeout and returns true/false
identifyDelegate.EndInvoke(out iresult, result); //code to run if WaitOne returns true
您可能希望这样做:

if(result.AsyncWaitHandle.WaitOne(timeout))
{
  identifyDelegate.EndInvoke(out iresult, result);
}
else
{
  //timeout occurred
  //handle timeout
}
更新:


您可能还想退房。这个问题似乎和你的差不多。此外,接受的答案还提供了一种可重复使用的方法来实施错误管理

我将其更改为您的建议,超时10秒。查询仍会偶尔锁定,但从未达到超时条件。什么可以阻止WaitHandle执行其工作?系统的行为与直接调用session.identify相同。我明白了。我相信你可能不得不强制中止需要很长时间才能响应的线程,这样你才能继续使用你的应用程序。我会更新我的答案