From 200c737e3508eee238e52a0243c8e1fa0b633e89 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sun, 3 Nov 2019 19:34:47 +0100 Subject: [PATCH] Run tasks from UIDispatcher.StartTask synchronously if we are already on the UI thread This removes the potential deadlock from creating a new task from the UI thread and then waiting for it. The new return value when we are already ion the UI thread is an already completed task. --- Rubberduck.Parsing/UIContext/UiDispatcher.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Rubberduck.Parsing/UIContext/UiDispatcher.cs b/Rubberduck.Parsing/UIContext/UiDispatcher.cs index 5a41187fca..43a929bd44 100644 --- a/Rubberduck.Parsing/UIContext/UiDispatcher.cs +++ b/Rubberduck.Parsing/UIContext/UiDispatcher.cs @@ -126,6 +126,12 @@ public Task StartTask(Action action, CancellationToken token, TaskCreationOption { CheckInitialization(); + if (_contextProvider.UiContext == SynchronizationContext.Current) + { + action.Invoke(); + return Task.CompletedTask; + } + return Task.Factory.StartNew(action, token, options, _contextProvider.UiTaskScheduler); } @@ -141,6 +147,12 @@ public Task StartTask(Func func, CancellationToken token, TaskCreationO { CheckInitialization(); + if (_contextProvider.UiContext == SynchronizationContext.Current) + { + var returnValue = func(); + return Task.FromResult(returnValue); + } + return Task.Factory.StartNew(func, token, options, _contextProvider.UiTaskScheduler); }