Skip to content
This repository was archived by the owner on Oct 4, 2021. It is now read-only.

Commit e441060

Browse files
authored
[Core] Avoid creating TaskCompletionSource on UI thread (#9392)
We don't need a completion source when already on the UI thread, so optimize the implementation a bit
1 parent 820173f commit e441060

File tree

1 file changed

+8
-8
lines changed
  • main/src/core/MonoDevelop.Core/MonoDevelop.Core

1 file changed

+8
-8
lines changed

main/src/core/MonoDevelop.Core/MonoDevelop.Core/Runtime.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -330,15 +330,15 @@ public static SynchronizationContext MainSynchronizationContext {
330330
/// </summary>
331331
public static Task RunInMainThread (Action action)
332332
{
333-
var ts = new TaskCompletionSource<int> ();
334333
if (IsMainThread) {
335334
try {
336335
action ();
337-
ts.SetResult (0);
336+
return Task.CompletedTask;
338337
} catch (Exception ex) {
339-
ts.SetException (ex);
338+
return Task.FromException (ex);
340339
}
341340
} else {
341+
var ts = new TaskCompletionSource<int> ();
342342
MainSynchronizationContext.Post (state => {
343343
var (act, tcs) = (ValueTuple<Action, TaskCompletionSource<int>>)state;
344344
try {
@@ -348,23 +348,23 @@ public static Task RunInMainThread (Action action)
348348
tcs.SetException (ex);
349349
}
350350
}, (action, ts));
351+
return ts.Task;
351352
}
352-
return ts.Task;
353353
}
354354

355355
/// <summary>
356356
/// Runs a function in the main thread (usually the UI thread). The method returns a task, so it can be awaited.
357357
/// </summary>
358358
public static Task<T> RunInMainThread<T> (Func<T> func)
359359
{
360-
var ts = new TaskCompletionSource<T> ();
361360
if (IsMainThread) {
362361
try {
363-
ts.SetResult (func ());
362+
return Task.FromResult (func ());
364363
} catch (Exception ex) {
365-
ts.SetException (ex);
364+
return Task.FromException<T> (ex);
366365
}
367366
} else {
367+
var ts = new TaskCompletionSource<T> ();
368368
MainSynchronizationContext.Post (state => {
369369
var (fun, tcs) = (ValueTuple<Func<T>, TaskCompletionSource<T>>)state;
370370
try {
@@ -373,8 +373,8 @@ public static Task<T> RunInMainThread<T> (Func<T> func)
373373
tcs.SetException (ex);
374374
}
375375
}, (func, ts));
376+
return ts.Task;
376377
}
377-
return ts.Task;
378378
}
379379

380380
/// <summary>

0 commit comments

Comments
 (0)