title: SQLite Asynchronous Task and the Wait operator - will Tasks execute in correct order?
body: <p>I have a SQLiteAsyncConnection Database with several tables and I want to get the Primary Key back after insert into one of them. My insert looks like this in the Database Model</p>
  
  <pre><code>    public Task SaveZoneAsync(Zone zone)
      {
          if (zone.ID == 0)
          {
              return database.InsertAsync(zone);
          }
          else
          {
              return database.UpdateAsync(zone);
          }
      }
  </code></pre>
  
  <p>also in the database model I have this method for getting the last inserted id from a given table.</p>
  
  <pre><code>    public async Task&lt;int&gt; GetLastInsertAsync(String tablename)
      {
          int x = await database.ExecuteScalarAsync&lt;int&gt;("SELECT last_insert_rowid() FROM " + tablename);
          return x;
      }
  </code></pre>
  
  <p>In my ViewModel I have this method and plan to pass a Zone object into it to insert into database</p>
  
  <pre><code>    public static int AddZoneToDB(Zone zone)
      {
          Task AddZone = Task.Factory.StartNew(() =&gt; App.Database.SaveZoneAsync(zone));
          AddZone.Wait();
          Task&lt;int&gt; getID = App.Database.GetLastInsertAsync("Zone");
          getID.RunSynchronously();
          int zoneID = getID.Result;
          return zoneID;
      }
  </code></pre>
  
  <p>and execute it like this</p>
  
  <pre><code>int zoneID = MapPageViewModel.AddZoneToDB(zoneToAdd);
  </code></pre>
  
  <p>My question is will the <code>AddZone.Wait()</code> in the <code>AddZoneToDB</code> method make sure that the <code>addZone</code> task is finished running before getting the int from <code>getID.Result</code>? Basically trying to make sure I always get the right ID from the correct record. I'm just not sure how <code>Wait()</code> and <code>RunSynchronously()</code> work together. This is a Xamarin SQLite db in Xamarin.Forms. ID is set as the primary key and to auto increment in the Zone model.</p>