title: How to fix "can only be called from the main thread" inside ContinueWith method
body: <p>I have a problem trying to manipulate GameObjects inside the ContinueWith method of a Task instance.
  The code below worked pretty well until we switched to .NET 4.x in Unity 2018.2.</p>
  
  <p>I've searched a lot and tought I found what it seems to be a workaround (using UnityThread), I could't find the reason why this code doesn't work anymore and since the same pattern is used a lot in my project I want to know if there is in fact no other solution.</p>
  
  <pre class="lang-c# prettyprint-override"><code>FirebaseDatabaseManager.Instance.GetPrivateChatMessages(chatId)
      .ContinueWith(messagesTask =&gt;
      {
          if (messagesTask.IsCompleted &amp;&amp; messagesTask.Result != null &amp;&amp; messagesTask.Result.Exists)
          {
              // Go over the dictionary in reverse.
              foreach (var message in messagesTask.Result.Children.OrderByDescending(x =&gt; x.Key))
              {
                  Debug.Log("Message " + message.Key);
  
                  // Insert the message as the first element.
                  StartCoroutine(AddMessageItem(message));
              }
          }
      });
  </code></pre>
  
  <p>EDIT: This is the method <code>GetPrivateChatMessages</code>.</p>
  
  <pre class="lang-c# prettyprint-override"><code>/// &lt;summary&gt;
  /// Returns the private chats' messages or null if the database is not initialized.
  /// &lt;/summary&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public Task&lt;DataSnapshot&gt; GetPrivateChatMessages(string chatId, int limit, string lastItemKey, long lastItemTimestamp)
  {
      if (!Initialized) return null;
  
      return DatabaseRoot.Child("messages").Child(chatId).OrderByChild("timestamp").EndAt(lastItemTimestamp, lastItemKey).LimitToLast(limit).GetValueAsync();
  }
  </code></pre>
  
  <p>Before the update the line                                     StartCoroutine(AddMessageItem(message));
  used to work just fine, now it throws an exception</p>
  
  <blockquote>
    <p>01-08 13:47:15.376 23882-24991/com.fhacktions E/Unity:<br>
    IsObjectMonoBehaviour can only be called from the main thread.<br>
    &ensp;&ensp;Constructors and field initializers will be executed from the
    loading thread when loading a scene.<br>
    &ensp;&ensp;Don't use this function in the
    constructor or field initializers, instead move initialization code to
    the Awake or Start function.<br>
    &ensp;&ensp;UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)<br>
    &ensp;&ensp;Fhacktions.c__AnonStorey2:&lt;>m__0(Task`1)<br>
    &ensp;&ensp;System.Threading.Tasks.Task:Execute()<br>
    &ensp;&ensp;System.Threading.ExecutionContext:RunInternal(ExecutionContext, ContextCallback, Object, Boolean)<br>
    &ensp;&ensp;System.Threading.ExecutionContext:Run(ExecutionContext, ContextCallback, Object, Boolean)<br>
    &ensp;&ensp;System.Threading.Tasks.Task:ExecuteWithThreadLocal(Task&amp;)<br>
    &ensp;&ensp;System.Threading.Tasks.Task:ExecuteEntry(Boolean)<br>
    &ensp;&ensp;System.Threading.ThreadPoolWorkQueue:Dispatch()<br>
    &ensp;&ensp;<br>
    &ensp;&ensp;[/Users/builduser/buildslave/unity/build/Runtime/Scripting/ScriptingThreadAndSerializationSafeCheck.cpp line 85]<br>
    &ensp;&ensp;(Filename: /Users/builduser/buildslave/unity/build/Runtime/Scripting/ScriptingThreadAndSerializationSafeCheck.cpp Li</p>
  </blockquote>
  
  <p><strong>EDIT</strong>: Passing TaskScheduler.FromCurrentSynchronizationContext() as a parameter to the ContinueWith method solved the problem, I guess the default implementation changed and that caused the problem after the switch. Thanks.</p>