title: C# have async function call synchronous function or synchronous function call async function
body: <p>I'm writing a C# .Net 4.5 library for doing common sql database operations (backup, restore, execute script, etc.).  I want to have both synchronous and asynchronous functions for each operation, as this library will be used by both console and GUI apps, but I don't want to duplicate code everywhere.  So as I see it, I have two options:</p>
  
  <ol>
  <li><p>Write the code that does the work in a synchronous function, and then just wrap it in a task for the async function, like so:</p>
  
  <pre><code>public void BackupDB(string server, string db)  
  {  
      // Do all of the work and long running operation here  
  }
  
  public async Task BackupDBAsync(string server, string db)  
  {  
      await Task.Factory.StartNew(() =&gt; BackupDB(server, db)).ConfigureAwait(false);  
  }
  </code></pre></li>
  <li><p>Write the code that does the work in an asynchronous function, and call it from a synchronous function using .Wait():</p>
  
  <pre><code>public async Task BackupDBAsync(string server, string db)  
  {  
      // Do all of the work and long running operation here, asynchronously.  
  }
  
  public void BackupDB(string server, string db)  
  {  
      BackupDBAsync(server, db).Wait(); // Execution will wait here until async function finishes completely.  
  }
  </code></pre></li>
  </ol>
  
  <p>Is one option better than the other?  Is one a best practice?  Or are there any other (better) alternatives?</p>
  
  <p>I know that one caveat to using .Wait() is that all of the await statements in the async function have to use .ConfigureAwait(false) to avoid deadlocks (<a href="https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c">as discussed here</a>), but since I'm writing a library that will never need to access the UI or WebContext I am safe to do that.</p>
  
  <p>I'll note too that the SQL library typically also has both synchronous and async functions that can be used, so if doing the work in the sync function, I would call their sync function, and if doing the work in the async function, I would call their async function.</p>
  
  <p>Thoughts/suggestions are appreciated.</p>
  
  <p>-- edit: I've also posted this question <a href="http://social.msdn.microsoft.com/Forums/en-US/async/thread/7bc69ba9-64b0-447e-b200-ca47c9fdce43" rel="nofollow noreferrer">on the MSDN forums here</a> to try and get an official MS response --</p>