2017-10-21 94 views
2

我正在C#中使用單個索引創建基於Lucene.Net的搜索引擎應用程序。作爲一項要求,我需要優化運行時間以進行包含多個(5)查詢的測試運行。因此,我想爲每個搜索使用一個單獨的線程,返回類似於this後的結果。我的代碼如下所示:Lucene.Net並行搜索

// load information needs 
List<InformationNeed> informationNeeds = FileReader.readInformationNeeds(collectionPath);    

// each search has its own thread referenced in this list 
List<Thread> threadList = new List<Thread>(); 

// each search has its own result referenced in this list 
List<SearchResult> searchResults = new List<SearchResult>(); 


foreach (InformationNeed informationNeed in informationNeeds){ 

    // create searchOptions 
    SearchOptions searchOptions = new SearchOptions(DEBUG_pre_processQuery, informationNeed.getInput()); 

    // run search 
    SearchResult result = null; // Used to store the return value 
    var thread = new Thread(
     () => 
     { 
     result = startSearch(searchOptions); 
     Console.WriteLine("end search for IN nr " + informationNeed.getID() + "results = " + result); 

     //add results to list 
     searchResults.Add(result); 

     }); 
    thread.Start(); 
    threadList.Add(thread); 
} 

// block main thread until all threads finished 
foreach (Thread t in threadList){ 
    t.Join(); 
} 

return searchResults; 

但是,我得到一個Lucene.Net.QueryParser.ParseException see screenshot依次運行搜索時我不明白。

如果我讓事情不清楚,請發表評論。我很感謝在這個問題上的任何幫助。

+0

您不同步對'searchResults'的訪問。這會導致問題。 –

回答

2

您需要同步對searchResults的訪問,否則多個線程將同時對其進行修改。或者,您可以使用異步模式,並從異步方法返回Task<SearchResult>,並且不爲每個線程使用相同的List

另外,在線程外聲明SearchResult result只是以與searchResults造成問題相同的方式請求問題。在線程中聲明它。

1

解決了它。在startSearch方法中,我有一個QueryParser的調用,它不是如here所述的線程安全。通過將lock添加到QueryParser實例來解決此問題。

+0

您是否也修復了對'searchResults'的非線程訪問? –

+0

是的,我也在那裏放了一個'鎖'。謝謝! – pad