Untity Synchronization context + Task.Run huge performance hit!

Code in the Task.Run runs under unity synchronization context for the first call (line 16).
After line 21 (SynchronizationContext.SetSynchronizationContext) the .net context is used for all Task.Run calls
In general Task.Run will also be run on a background thread by unity - however the problem lies when you want to execute something on the main-thread.

I am using TaskFactory to Run a Task on the unity main thread (the _mts variable contains the main thread scheduler). However the Unity default scheduler will only execute one task per frame, which can take a very long time if many tasks are run in the background that synchronize to the main thread. With the .Net Default Scheduler this works way better (because it handles multiple synchronizations per frame)

In the meantime I can recommend to use UniTask instead: https://github.com/Cysharp/UniTask - as it solves a lot of the problems (including handling exceptions from background tasks). It also handles switching to main thread much more efficiently.

Also in future versions Unity will support async/await natively which I’m quite excited about, see:
https://discussions.unity.com/t/836646 page-16#post-8024567