Skip to content

Commit

Permalink
Merge pull request #2861 from Wox-launcher/bao
Browse files Browse the repository at this point in the history
performace improvement by using cancellation token
  • Loading branch information
bao-qian authored Apr 24, 2020
2 parents c6ec2fc + deaca88 commit 36d72f1
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 36 deletions.
4 changes: 2 additions & 2 deletions Plugins/Wox.Plugin.Program/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,12 @@ public static void IndexPrograms()
{
var a = Task.Run(() =>
{
Logger.StopWatchNormal("UWP Program index cost", IndexWin32Programs);
Logger.StopWatchNormal("Win32 index cost", IndexWin32Programs);
});

var b = Task.Run(() =>
{
Logger.StopWatchNormal("UWP Program index cost", IndexUWPPrograms);
Logger.StopWatchNormal("UWP index cost", IndexUWPPrograms);
});

Task.WaitAll(a, b);
Expand Down
15 changes: 13 additions & 2 deletions Wox.Infrastructure/Logger/Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,17 @@ private static void ExceptionInternal(string classAndMethod, string message, Sys
logger.Error("-------------------------- End exception --------------------------");
}

public static void WoxTrace(this NLog.Logger logger, string message, [CallerMemberName] string methodName = "")
{
// need change logging manually to see trace log
if (logger.IsTraceEnabled)
{
Debug.WriteLine($"DEBUG|{logger.Name}|{methodName}|{message}");
logger.Trace($"{methodName}|{message}");
}

}

public static void WoxDebug(this NLog.Logger logger, string message, [CallerMemberName] string methodName = "")
{
Debug.WriteLine($"DEBUG|{logger.Name}|{methodName}|{message}");
Expand All @@ -70,13 +81,13 @@ public static void WoxDebug(this NLog.Logger logger, string message, [CallerMemb
public static void WoxInfo(this NLog.Logger logger, string message, [CallerMemberName] string methodName = "")
{
Debug.WriteLine($"INFO|{logger.Name}|{methodName}|{message}");
logger.Debug($"{methodName}|{message}");
logger.Info($"{methodName}|{message}");
}

public static void WoxError(this NLog.Logger logger, string message, [CallerMemberName] string methodName = "")
{
Debug.WriteLine($"ERROR|{logger.Name}|{methodName}|{message}");
logger.Debug($"{methodName}|{message}");
logger.Error($"{methodName}|{message}");
}

public static void WoxError(this NLog.Logger logger, string message, System.Exception exception, [CallerMemberName] string methodName = "")
Expand Down
2 changes: 1 addition & 1 deletion Wox/PublicAPIInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public void StartLoadingBar()

public void StopLoadingBar()
{
_mainVM.ProgressBarVisibility = Visibility.Collapsed;
_mainVM.ProgressBarVisibility = Visibility.Hidden;
}

public void InstallPlugin(string path)
Expand Down
63 changes: 37 additions & 26 deletions Wox/ViewModel/MainViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ public class MainViewModel : BaseModel, ISavable
{
#region Private Fields

private bool _isQueryRunning;
private Query _lastQuery;
private string _queryTextBeforeLeaveResults;

Expand Down Expand Up @@ -92,11 +91,14 @@ private void RegisterResultsUpdatedEvent()
var plugin = (IResultUpdated)pair.Plugin;
plugin.ResultsUpdated += (s, e) =>
{
var token = _updateToken;
Task.Run(() =>
{
if (token.IsCancellationRequested) { return; }
PluginManager.UpdatePluginMetadata(e.Results, pair.Metadata, e.Query);
if (token.IsCancellationRequested) { return; }
UpdateResultView(e.Results, pair.Metadata, e.Query);
}, _updateToken);
}, token);
};
}
}
Expand Down Expand Up @@ -221,7 +223,7 @@ public string QueryText
Query();
}
}

/// <summary>
/// we need move cursor to end when we manually changed query
/// but we don't want to move cursor to end when query is updated from TextBox
Expand Down Expand Up @@ -378,62 +380,71 @@ private void QueryHistory()

private void QueryResults()
{
if (!string.IsNullOrEmpty(QueryText))
if (_updateSource != null && !_updateSource.IsCancellationRequested)
{
_updateSource?.Cancel();
var currentUpdateSource = new CancellationTokenSource();
_updateSource = currentUpdateSource;
var currentCancellationToken = _updateSource.Token;
_updateToken = currentCancellationToken;
_updateSource.Cancel();
_updateSource.Dispose();
}
var updateSource = new CancellationTokenSource();
_updateSource = updateSource;
var token = updateSource.Token;
_updateToken = token;

ProgressBarVisibility = Visibility.Hidden;
_isQueryRunning = true;
var query = QueryBuilder.Build(QueryText.Trim(), PluginManager.NonGlobalPlugins);
ProgressBarVisibility = Visibility.Hidden;
var queryText = QueryText.Trim();
if (!string.IsNullOrEmpty(queryText))
{
if (token.IsCancellationRequested) { return; }
var query = QueryBuilder.Build(queryText, PluginManager.NonGlobalPlugins);
if (query != null)
{
// handle the exclusiveness of plugin using action keyword
RemoveOldQueryResults(query);

_lastQuery = query;
Task.Delay(200, currentCancellationToken).ContinueWith(_ =>
{ // start the progress bar if query takes more than 200 ms and this is the current running query and it didn't finish yet
if (currentUpdateSource == _updateSource && _isQueryRunning)

Task.Delay(200, token).ContinueWith(_ =>
{ // start the progress bar if query takes more than 200 ms
if (!token.IsCancellationRequested)
{
ProgressBarVisibility = Visibility.Visible;
Logger.WoxInfo($"progressbar visible {query} {token.IsCancellationRequested} {ProgressBarVisibility}");
}
}, currentCancellationToken);
}, token);

var plugins = PluginManager.ValidPluginsForQuery(query);
Task.Run(() =>
{
if (token.IsCancellationRequested) { return; }
var plugins = PluginManager.ValidPluginsForQuery(query);

// so looping will stop once it was cancelled
var parallelOptions = new ParallelOptions { CancellationToken = currentCancellationToken };
var parallelOptions = new ParallelOptions { CancellationToken = token };
try
{
Parallel.ForEach(plugins, parallelOptions, plugin =>
{
if (!plugin.Metadata.Disabled)
{
if (token.IsCancellationRequested) { return; }
var results = PluginManager.QueryForPlugin(plugin, query);
if (token.IsCancellationRequested) { return; }
UpdateResultView(results, plugin.Metadata, query);
}
});
}
catch (OperationCanceledException)
{
// nothing to do here
Logger.WoxInfo($"canceled {query}");
}


// this should happen once after all queries are done so progress bar should continue
// until the end of all querying
_isQueryRunning = false;
if (currentUpdateSource == _updateSource)
Logger.WoxInfo($"canceled {query} {token.IsCancellationRequested}");
if (!token.IsCancellationRequested)
{ // update to hidden if this is still the current query
ProgressBarVisibility = Visibility.Hidden;
updateSource.Cancel();
updateSource.Dispose();
Logger.WoxInfo($"progressbard hidden {query} {token.IsCancellationRequested} {ProgressBarVisibility}");
}
}, currentCancellationToken);
}, token);
}
}
else
Expand Down
10 changes: 5 additions & 5 deletions Wox/ViewModel/ResultsViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -283,16 +283,16 @@ public void Update(List<ResultViewModel> newItems)

for (int i = 0; i < location; i++)
{
ResultViewModel oldResult = this[i];
ResultViewModel oldResult = this[i];
ResultViewModel newResult = newItems[i];
Logger.WoxDebug(
Logger.WoxTrace(
$"index {i} " +
$"old<{oldResult.Result.Title} {oldResult.Result.Score}> " +
$"new<{newResult.Result.Title} {newResult.Result.Score}>"
);
if (oldResult.Equals(newResult))
{
Logger.WoxDebug($"index <{i}> equal");
Logger.WoxTrace($"index <{i}> equal");
// update following info no matter they are equal or not
// because check equality will cause more computation
this[i].Result.Score = newResult.Result.Score;
Expand All @@ -303,7 +303,7 @@ public void Update(List<ResultViewModel> newItems)
{
// result is not the same update it in the current index
this[i] = newResult;
Logger.WoxDebug($"index <{i}> not equal old<{oldResult.GetHashCode()}> new<{newResult.GetHashCode()}>");
Logger.WoxTrace($"index <{i}> not equal old<{oldResult.GetHashCode()}> new<{newResult.GetHashCode()}>");
}
}

Expand All @@ -312,7 +312,7 @@ public void Update(List<ResultViewModel> newItems)
{
for (int i = oldCount; i < newCount; i++)
{
Logger.WoxDebug($"Logger.WoxErroradd index {i} new<{newItems[i].Result.Title}");
Logger.WoxTrace($"add {i} new<{newItems[i].Result.Title}");
Add(newItems[i]);
}
}
Expand Down

0 comments on commit 36d72f1

Please sign in to comment.