Friday, June 6, 2014

Start may not be called on a promise-style task.

             Recently i have faced this issue . The problem here is  The await keyword inside your asynchronous method is trying to come back to the UI thread.Since the User Interface  thread is busy and waiting for the entire task to complete, you have a deadlock.Moving the async call to Task.Run() solves the issue.Because the async call is now running on a thread pool thread, it doesn't try to come back to the UI thread, and everything therefore works.

               Alternatively, you can call StartAsTask().ConfigureAwait(false) before awaiting the inner operation to make it come back to the thread pool rather than the UI thread, avoiding the deadlock entirely.

 

Here is the working code to avoid the above exception

  1: private void GetData(string text)
  2: {
  3:     var task = Task.Run(async () => { await GetDataAsync(sqlQuery); });
  4:     task.Wait();
  5: }
  6: 

No comments:

Post a Comment