【问题标题】:Lucene.Net Parallel SearchLucene.Net 并行搜索
【发布时间】:2017-10-21 19:23:41
【问题描述】:

我正在用 C# 创建一个基于 Lucene.Net 的搜索引擎应用程序,它只有一个索引。作为一项要求,我需要为具有多个 (5) 查询的测试运行优化运行时。因此,我想为每个搜索使用一个单独的线程,返回类似于this 帖子的结果。我的代码如下所示:

// 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,在按顺序运行搜索时我没有得到。

如果我有不清楚的地方,请发表评论。对于这个问题,我将不胜感激。

【问题讨论】:

  • 您没有同步访问searchResults。这会导致问题。

标签: c# multithreading lucene.net


【解决方案1】:

需要同步访问searchResults,否则多个线程会同时修改。或者您可以使用异步模式并从您的异步方法返回一个Task&lt;SearchResult&gt;,而不是为每个线程使用相同的List

此外,在线程外声明SearchResult result 只是在自找麻烦,就像searchResults 造成问题一样。在线程内声明它。

【讨论】:

    【解决方案2】:

    解决了。在startSearch 方法中,我调用了QueryParser,这不是here 所述的线程安全。通过将lock 添加到QueryParser 实例来解决此问题。

    【讨论】:

    • 是的,我还在那里放了一个lock。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    相关资源
    最近更新 更多