2011-08-07 19 views
0

我正在使用C#中的LogParser 2.2通過COM互操作,並希望能夠給長時間運行的查詢一個超時。是否可以安全地從C#中取消長時間運行的LogParser查詢?

例如

var ctx = new COMIISW3CInputContextClassClass(); 
var log = new LogQueryClassClass(); 
var rs = log.Execute(qry, ctx); 

如果時間太長,是否可以中斷log.Execute呼叫? 我試過Thread.Abort(),但它看起來是ThreadAbortException等待Execute調用正常結束。

用於測試Thread.Abort()的代碼是:

var ctx = new COMIISW3CInputContextClassClass(); 
var log = new LogQueryClassClass(); 
ILogRecordset rs = null; 
var t = new Thread(() => 
    { 
     rs = log.Execute(qry, ctx); 
    }); 
t.SetApartmentState(ApartmentState.STA); 
t.Start(); 

t.Join(100); 
t.Abort(); 

// this tests if the file lock is still held by log parser 
Assert.Throws<IOException>(() => 
    File.OpenWrite(path)); 

t.join(10000); 

// file is no longer locked 
using (File.OpenWrite(path)) 
    Assert.IsTrue(true); 
+0

一個可能的解決方法可以是在啓動一個單獨的應用程序域上面的代碼和殺死的AppDomain如果LOGPARSER的是忙。 –

+0

我擔心我會發現AppDomain的行爲方式是相同的(等到COM調用返回前清理)。我想我需要測試它並找出答案。 –

回答

0

Thread.Abort取消執行很少安全。這種情況並不安全,因爲無法知道Log Parser數據結構的狀態。您可以在使用標準輸入/輸出,命名管道,WCF或您最喜愛的IPC技術進行通信的單獨進程中執行查詢。然後要取消查詢,請在該過程中使用Process.Kill

注意:不知道Log Parser是否寫入任何會留下的臨時文件。除此之外,Windows應該爲您正確清理所有狀態。