2017-10-21 167 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