Question

I'm making a windows phone game with Unity3d and I have the need to call a method from the Unity thread asynchronously from the UI thread.

This all works, however with one particular method the first execution executes as expected however after the second it seems to lock up the game.

private async static Task<String> ShowDescriptionProductListing()
    {
        var x = await CurrentApp.LoadListingInformationAsync();

        StringBuilder builder = new StringBuilder();

        builder.AppendFormat("{0}\n{1}", x.Description,
                                     x.ProductListings.FirstOrDefault().Value);

        return builder.ToString();
    }
    public static void ShowDescrProduct()
    {
        string x = ShowDescriptionProductListing().Result;
        MessageBox.Show(x);

    }

I think the line:

 var x = await CurrentApp.LoadListingInformationAsync();

Is most likely the culprit, however I'm having a hard time debugging it.

The class which 'holds' that method in unity is like so:

public static class HelperClass
{
   public static void ShowDescrProduct()
   {
          Dispatcherr.InvokeOnUIThread(Tests.ShowDescrProduct); //The method above
   }
}

Dispatcherr (Yeah i need to use namespaces haha) just holds two Action properties that I set inside the UI thread.

    public void EnterUIThread(Action action)
    {
        Dispatcher.BeginInvoke(() => 
        {
            action();
        });
    }

    private void Unity_Loaded()
    {
        Dispatcherr.InvokeUIThread = EnterUIThread; //One of the actions I just 
                                                  //mentioned being assigned the above
                                                  //method
    }

And it's in the EnterUIThread call to Dispatcher.BeginInvoke that it seems to get locked up, only after the first call - which is always successful.

Confusing me slightly to say the least.

Anyone able to give any insight?

Thanks in advance

Was it helpful?

Solution

You're calling Result on the asynchronous operation. This is going to cause the UI thread to block until the asynchronous operation finishes. The asynchronous operation needs to wait for the UI thread to be free so that the continuation to LoadListingInformationAsync can be scheduled in the UI thread.

Both operations are waiting on each other to finish. Deadlock.

You need to not block the UI thread while waiting for this operation to finish. You should await it instead, making ShowDescrProduct and async method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top