Cancel a user's search using lock and session ID

故事扮演 提交于 2020-01-16 04:14:05

问题


My MVC application is handling searches via a standard search box on a webpage. I'm trying to keep track of a user's searches - if they type a new search then I want to cancel their previous search and launch the new one.

I'm using a dictionary of sessionIDs and Searcher objects (my object that has a method Search() in it.

The issue I'm having is the flag to say SearchInProgress is never appearing as false and so the function that cancels a search is never called. Possibly due to using a lock..? Here is the code in question:

 public SearchResultModel Search(string sessionId, string query, long time) {

    SearchResultModel results;

    lock (_lock) {
      if (_searches.ContainsKey(sessionId)) { // Check if this user (by sessionId) has already searched at all
        if (_searches[sessionId].SearchInProgress) { // Is there a search already in progress, and if so cancel it!
          _searches[sessionId].Cancel();

          while (_searches[sessionId].WaitingForCancel()) {
            // Waiting for cancel to complete - I'll replace this with a Timer later
          }
        }
      }
      else { // If user hasn't searched before then they'll need a searcher instance
        Searcher searcher = new Searcher();
        _searches[sessionId] = searcher;
      }
    }

    results = _searches[sessionId].Search(Db, query);
    results.time = time;
    return results;
}

Also, the class contains the following static members:

private static object _lock = new object();
private static Dictionary<string, Searcher> _searches;

SearchInProgress is a member variable of Searcher and is set to false on construction and then true when the Search() function is called... and then false again just before Search() returns the results.

来源:https://stackoverflow.com/questions/16315731/cancel-a-users-search-using-lock-and-session-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!