0

I am getting some issues returning data from azure mobile backend api using android emulator. The mobile app is written with Xamarin and I am using MobileServiceClient and IMobileServiceSyncTable. The following is what I have coded:

var _mobileServiceClient = new MobileServiceClient(url);
var store = new MobileServiceSQLiteStore("notesdb.db");
store.DefineTable<Notes>();
_mobileServiceClient.SyncContext.InitializeAsync(store);
var _notesTable = _mobileServiceClient.GetSyncTable<Notes>();

var temp = await _notesTable.ReadAsync();

Backend code is as followed:

public IQueryable<Notes> GetAllNotes()
{
    return Query(); 
}

Whenever I do that, the app will become unresponsive and never returned. Its like it is in deadlock mode.

Has anyone had this problem?

developer
  • 718
  • 9
  • 28
  • Avoid mixing async/await and blocking calls like .Wait() or .Result . Refactor your code to be async all the way through. Check https://stackoverflow.com/questions/57456895/xamarin-forms-httpclient-class-getstringasync-and-getasync-return-null-value – Lucas Zhang Aug 13 '19 at 07:45

1 Answers1

1

After looking at the MobileServiceClient usage: https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-dotnet-how-to-use-client-library

Your calls seem fine except one:

_mobileServiceClient.SyncContext.InitializeAsync(store);

Since you are not awaiting this method, the sync context will not be initialized for your next methods.

So just await the method and you should be fine:

await _mobileServiceClient.SyncContext.InitializeAsync(store);

One general rule your can apply almost everytime: always await the methods returning Task objects.

Also since you are in the service/repository layer, you should ConfigureAwait(false) your methods:

var _mobileServiceClient = new MobileServiceClient(url);
var store = new MobileServiceSQLiteStore("notesdb.db");
store.DefineTable<Notes>();
await _mobileServiceClient.SyncContext.InitializeAsync(store).ConfigureAwait(false);
var _notesTable = _mobileServiceClient.GetSyncTable<Notes>();

var temp = await _notesTable.ReadAsync().ConfigureAwait(false);

Doing that your code won't run in the UI thread (well it's not guaranteed but I don't want to confuse you :). Since you are not running the code on the same thread, it will also reduce possible deadlocks.

more on that: https://medium.com/bynder-tech/c-why-you-should-use-configureawait-false-in-your-library-code-d7837dce3d7f

Roubachof
  • 3,351
  • 3
  • 23
  • 34