From 6863b412e3060f3ff1d69a08c40891fb5d5182ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=98=E9=9F=AC=20=E5=BC=A0?= Date: Fri, 20 Nov 2020 22:45:33 +0800 Subject: [PATCH] Use TPL's BufferBlock instead of BlockingCollection, which will block the current Thread. This should make the Task.Run works better. --- Flow.Launcher/ViewModel/MainViewModel.cs | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Flow.Launcher/ViewModel/MainViewModel.cs b/Flow.Launcher/ViewModel/MainViewModel.cs index ccc351cd3..b6bb6703a 100644 --- a/Flow.Launcher/ViewModel/MainViewModel.cs +++ b/Flow.Launcher/ViewModel/MainViewModel.cs @@ -23,6 +23,7 @@ using System.Windows.Media; using Flow.Launcher.Infrastructure.Image; using System.Collections.Concurrent; using Flow.Launcher.Infrastructure.Logger; +using System.Threading.Tasks.Dataflow; namespace Flow.Launcher.ViewModel { @@ -49,7 +50,7 @@ namespace Flow.Launcher.ViewModel private bool _saved; private readonly Internationalization _translator = InternationalizationManager.Instance; - private BlockingCollection _resultsUpdateQueue; + private BufferBlock _resultsUpdateQueue; #endregion @@ -94,10 +95,10 @@ namespace Flow.Launcher.ViewModel var plugin = (IResultUpdated)pair.Plugin; plugin.ResultsUpdated += (s, e) => { - Task.Run(() => + Task.Run(async () => { PluginManager.UpdatePluginMetadata(e.Results, pair.Metadata, e.Query); - _resultsUpdateQueue.Add(new ResultsForUpdate(e.Results, pair.Metadata, e.Query, _updateToken)); + await _resultsUpdateQueue.SendAsync(new ResultsForUpdate(e.Results, pair.Metadata, e.Query, _updateToken)); }, _updateToken); }; } @@ -105,20 +106,14 @@ namespace Flow.Launcher.ViewModel private void RegisterResultUpdate() { - _resultsUpdateQueue = new BlockingCollection(); + _resultsUpdateQueue = new BufferBlock(); Task.Run(async () => { - while (true) + while (await _resultsUpdateQueue.OutputAvailableAsync()) { - List queue = new List() { _resultsUpdateQueue.Take() }; await Task.Delay(30); - - while (_resultsUpdateQueue.TryTake(out var resultsForUpdate)) - { - queue.Add(resultsForUpdate); - } - + _resultsUpdateQueue.TryReceiveAll(out var queue); UpdateResultView(queue.Where(r => !r.Token.IsCancellationRequested)); } @@ -443,7 +438,7 @@ namespace Flow.Launcher.ViewModel if (!plugin.Metadata.Disabled) { var results = PluginManager.QueryForPlugin(plugin, query); - _resultsUpdateQueue.Add(new ResultsForUpdate(results, plugin.Metadata, query, currentCancellationToken)); + _resultsUpdateQueue.Post(new ResultsForUpdate(results, plugin.Metadata, query, currentCancellationToken)); } }); }