Skip to content

Commit 92be6fd

Browse files
committed
Use Task.Yield to avoid using Parallel.For
1 parent c939924 commit 92be6fd

File tree

1 file changed

+28
-31
lines changed

1 file changed

+28
-31
lines changed

Flow.Launcher/ViewModel/MainViewModel.cs

Lines changed: 28 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ private void RegisterResultsUpdatedEvent()
8686
{
8787
foreach (var pair in PluginManager.GetPluginsForInterface<IResultUpdated>())
8888
{
89-
var plugin = (IResultUpdated)pair.Plugin;
89+
var plugin = (IResultUpdated) pair.Plugin;
9090
plugin.ResultsUpdated += (s, e) =>
9191
{
9292
Task.Run(() =>
@@ -113,25 +113,13 @@ private void InitializeKeyCommands()
113113
}
114114
});
115115

116-
SelectNextItemCommand = new RelayCommand(_ =>
117-
{
118-
SelectedResults.SelectNextResult();
119-
});
116+
SelectNextItemCommand = new RelayCommand(_ => { SelectedResults.SelectNextResult(); });
120117

121-
SelectPrevItemCommand = new RelayCommand(_ =>
122-
{
123-
SelectedResults.SelectPrevResult();
124-
});
118+
SelectPrevItemCommand = new RelayCommand(_ => { SelectedResults.SelectPrevResult(); });
125119

126-
SelectNextPageCommand = new RelayCommand(_ =>
127-
{
128-
SelectedResults.SelectNextPage();
129-
});
120+
SelectNextPageCommand = new RelayCommand(_ => { SelectedResults.SelectNextPage(); });
130121

131-
SelectPrevPageCommand = new RelayCommand(_ =>
132-
{
133-
SelectedResults.SelectPrevPage();
134-
});
122+
SelectPrevPageCommand = new RelayCommand(_ => { SelectedResults.SelectPrevPage(); });
135123

136124
SelectFirstResultCommand = new RelayCommand(_ => SelectedResults.SelectFirstResult());
137125

@@ -209,6 +197,7 @@ private void InitializeKeyCommands()
209197
public ResultsViewModel History { get; private set; }
210198

211199
private string _queryText;
200+
212201
public string QueryText
213202
{
214203
get { return _queryText; }
@@ -229,10 +218,12 @@ public void ChangeQueryText(string queryText)
229218
QueryTextCursorMovedToEnd = true;
230219
QueryText = queryText;
231220
}
221+
232222
public bool LastQuerySelected { get; set; }
233223
public bool QueryTextCursorMovedToEnd { get; set; }
234224

235225
private ResultsViewModel _selectedResults;
226+
236227
private ResultsViewModel SelectedResults
237228
{
238229
get { return _selectedResults; }
@@ -264,6 +255,7 @@ private ResultsViewModel SelectedResults
264255
QueryText = string.Empty;
265256
}
266257
}
258+
267259
_selectedResults.Visbility = Visibility.Visible;
268260
}
269261
}
@@ -324,7 +316,7 @@ private void QueryContextMenu()
324316
var filtered = results.Where
325317
(
326318
r => StringMatcher.FuzzySearch(query, r.Title).IsSearchPrecisionScoreMet()
327-
|| StringMatcher.FuzzySearch(query, r.SubTitle).IsSearchPrecisionScoreMet()
319+
|| StringMatcher.FuzzySearch(query, r.SubTitle).IsSearchPrecisionScoreMet()
328320
).ToList();
329321
ContextMenu.AddResults(filtered, id);
330322
}
@@ -351,7 +343,7 @@ private void QueryHistory()
351343
Title = string.Format(title, h.Query),
352344
SubTitle = string.Format(time, h.ExecutedDateTime),
353345
IcoPath = "Images\\history.png",
354-
OriginQuery = new Query { RawQuery = h.Query },
346+
OriginQuery = new Query {RawQuery = h.Query},
355347
Action = _ =>
356348
{
357349
SelectedResults = Results;
@@ -397,7 +389,8 @@ private void QueryResults()
397389

398390
_lastQuery = query;
399391
Task.Delay(200, currentCancellationToken).ContinueWith(_ =>
400-
{ // start the progress bar if query takes more than 200 ms and this is the current running query and it didn't finish yet
392+
{
393+
// start the progress bar if query takes more than 200 ms and this is the current running query and it didn't finish yet
401394
if (currentUpdateSource == _updateSource && _isQueryRunning)
402395
{
403396
ProgressBarVisibility = Visibility.Visible;
@@ -410,17 +403,14 @@ private void QueryResults()
410403
// so looping will stop once it was cancelled
411404

412405
Task[] tasks = new Task[plugins.Count];
413-
var parallelOptions = new ParallelOptions { CancellationToken = currentCancellationToken };
414406
try
415407
{
416-
Parallel.For(0, plugins.Count, parallelOptions, i =>
408+
for (var i = 0; i < plugins.Count; i++)
417409
{
418410
if (!plugins[i].Metadata.Disabled)
419-
{
420411
tasks[i] = QueryTask(plugins[i], query, currentCancellationToken);
421-
}
422412
else tasks[i] = Task.CompletedTask; // Avoid Null
423-
});
413+
}
424414

425415
// Check the code, WhenAll will translate all type of IEnumerable or Collection to Array, so make an array at first
426416
await Task.WhenAll(tasks);
@@ -434,20 +424,25 @@ private void QueryResults()
434424
// until the end of all querying
435425
_isQueryRunning = false;
436426
if (!currentCancellationToken.IsCancellationRequested)
437-
{ // update to hidden if this is still the current query
427+
{
428+
// update to hidden if this is still the current query
438429
ProgressBarVisibility = Visibility.Hidden;
439430
}
440431

441432
// Local Function
442433
async Task QueryTask(PluginPair plugin, Query query, CancellationToken token)
443434
{
435+
// Since it is wrapped within a Task.Run, the synchronous context is null
436+
// Task.Yield will force it to run in ThreadPool
437+
await Task.Yield();
438+
444439
var results = await PluginManager.QueryForPlugin(plugin, query, token);
445440
if (!currentCancellationToken.IsCancellationRequested)
446441
UpdateResultView(results, plugin.Metadata, query);
447442
}
448-
449-
}, currentCancellationToken).ContinueWith(t => Log.Exception("|MainViewModel|Plugins Query Exceptions", t.Exception),
450-
TaskContinuationOptions.OnlyOnFaulted);
443+
}, currentCancellationToken).ContinueWith(
444+
t => Log.Exception("|MainViewModel|Plugins Query Exceptions", t.Exception),
445+
TaskContinuationOptions.OnlyOnFaulted);
451446
}
452447
}
453448
else
@@ -514,6 +509,7 @@ private Result ContextMenuTopMost(Result result)
514509
}
515510
};
516511
}
512+
517513
return menu;
518514
}
519515

@@ -559,6 +555,7 @@ private bool HistorySelected()
559555
var selected = SelectedResults == History;
560556
return selected;
561557
}
558+
562559
#region Hotkey
563560

564561
private void SetHotkey(string hotkeyStr, EventHandler<HotkeyEventArgs> action)
@@ -577,7 +574,8 @@ private void SetHotkey(HotkeyModel hotkey, EventHandler<HotkeyEventArgs> action)
577574
catch (Exception)
578575
{
579576
string errorMsg =
580-
string.Format(InternationalizationManager.Instance.GetTranslation("registerHotkeyFailed"), hotkeyStr);
577+
string.Format(InternationalizationManager.Instance.GetTranslation("registerHotkeyFailed"),
578+
hotkeyStr);
581579
MessageBox.Show(errorMsg);
582580
}
583581
}
@@ -627,7 +625,6 @@ private void OnHotkey(object sender, HotkeyEventArgs e)
627625
{
628626
if (!ShouldIgnoreHotkeys())
629627
{
630-
631628
if (_settings.LastQueryMode == LastQueryMode.Empty)
632629
{
633630
ChangeQueryText(string.Empty);

0 commit comments

Comments
 (0)