Bug 12681

Summary: Task.Wait() blocks forever, and I don't know why.
Product: Android Reporter: Jonathan Pryor <jonp>
Component: BCL Class LibrariesAssignee: Jonathan Pryor <jonp>
Severity: normal CC: mono-bugs+monodroid
Priority: ---    
Version: 4.8.x   
Target Milestone: ---   
Hardware: PC   
OS: Mac OS   
Tags: Is this bug a regression?: ---
Last known good build:
Attachments: Scratch.TaskWaitDeadlock.zip

Description Jonathan Pryor 2013-06-13 17:12:30 UTC
Created attachment 4113 [details]

Consider the Scratch.TaskWaitDeadlocks project. The core method is this:

  void DownloadUrl ()
    var cb = ServicePointManager.ServerCertificateValidationCallback;
    ServicePointManager.ServerCertificateValidationCallback = 
        (s, cert, chain, policy) => {
      Console.WriteLine ("# ServerCertificateValidationCallback");
      return true;

    string url = "https://pipeline.internalx.com/";
    TaskStatus status     = 0;
    Exception  exception  = null;
    var downloadTask = new WebClient ().DownloadDataTaskAsync (url);
    var completeTask = downloadTask.ContinueWith (t => {
        Console.WriteLine ("# DownloadDataTaskAsync complete; " +
            "status={0}; exception={1}", t.Status, t.Exception);
        status    = t.Status;
        exception = t.Exception;
    Console.WriteLine ("# downloadTask.Status={0}; completeTask.Status={1}",
        downloadTask.Status, completeTask.Status);
    Console.WriteLine ("# BEFORE Wait()");
    completeTask.Wait ();
    Console.WriteLine ("# AFTER Wait()");
    ServicePointManager.ServerCertificateValidationCallback = cb;
    if (status != TaskStatus.RanToCompletion)
      throw new InvalidOperationException ("Unable to download URL! Status: " +
          status + "; Exception=" + exception);

If I execute that method in a "normal" console-app, it works as expected.

If I execute that method in a Xamarin.Android app, `completeTask.Wait()` never returns.

If I REMOVE `completeTask.Wait()` (and everything after it...), `completeTask` IS executed (as I see the "DownloadDataTaskAsync complete" message in `adb logcat`).

Thus, something specific to the Xamarin.Android environment is preventing Task.Wait() from ever returning.
Comment 1 Jonathan Pryor 2013-06-13 18:14:41 UTC
Not a bug; by design.

WebClient.DownloadDataTaskAsync() is an `async` method, and when started from the UI thread will call back onto the UI thread as part of the semantics. Since DownloadUrl() is executed from the UI thread and is waiting for a callback to the UI thread to complete, we have deadlock, and I'm a sad panda.

Doing the ~same thing in WPF has the same result, so this is intended behavior.