2009-07-15 19 views
0

「session.identify」是我稱之爲無法訪問的第三方COM API。它執行一個服務器查詢,不知何故偶爾會鎖定(並因此暫停正在等待結果的主程序)。AsyncWaitHandle終止正確實施的第三方API?

我的嘗試是將它包裝在一個AsyncDelegate中,這樣我就可以給它一個超時時間,並且在超時過期後允許主程序繼續(類似於this one,只是返回值)。然而,它仍然鎖定,沒有超時的影響。

我是否錯誤地使用了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; 
} 

回答

1

從我可以從http://msdn.microsoft.com/en-us/library/kzy257t0.aspx明白,你應該有WaitOne的()方法的返回值的邏輯檢查,如果超時環繞該

你的邏輯你正在運行的是不管的EndInvoke ocurrs與否,因此你會從session.Identify獲得相同的timout錯誤。

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 
} 

UPDATE:

你可能也想看看this SO thread。這個問題似乎與您的問題完全相同。此外,接受的答案提供了一種可重複使用的方式來實現錯誤管理

+0

我改變它爲您的建議與10秒超時。查詢仍然偶爾會鎖定,但超時條件永遠不會達到。什麼能阻止WaitHandle的工作? – Hauke 2009-07-17 09:50:02