2

I'm developing an Android App with Xamarin. I have a static class NetworkServices that exposes some method to call webservices. One of them, query server status:

public static async Task<SystemInfo> TestConnection(HomeServerInfo hsi)
        {
            HttpClient openRequest = new HttpClient();
            HttpResponseMessage hrm = await openRequest.GetAsync(new System.Uri(hsi.ToString() + "/HomeServices/ServerController"));

            return new SystemInfo(hrm.ToString());
        }

This method is called from the OnCreate:

// Query server status
            Task<SystemInfo> si = NetworkServices.TestConnection(hsi);
            serverStatus.SetText(si.Result.CurrentDateTime, TextView.BufferType.Normal);

but this freeze the app. Why is wrong? The query Result property is not correct? Thank you

1 Answers1

0

You should run your task in background and continue it with UI update on UI Thread.

// Query server status
Task<SystemInfo> si = NetworkServices.TestConnection(hsi);
si.ContinueWith((result) =>
{
   using(var h = new Handler(Looper.MainLooper))
   {
      h.Post(()=>serverStatus.SetText(result.CurrentDateTime, TextView.BufferType.Normal));
   }
}

si.Start();
nevalenny
  • 71
  • 6
  • Thank you! I'm a bit confused... TestConnection returns a Task object. When I call for Result property the Task i executed? Or the UI thread waits until complete? Can you explain me a bit? – Old-fashioned-dev Nov 20 '16 at 15:52
  • Exactly! The getter of Result property of Task is equivalent to Wait until the task finished. And since you execute it on main thread (inside onCreate()) you block your app until Result is computed. And you right - accessing Result property gets task executed in current context. http://stackoverflow.com/questions/12484112/what-happens-while-waiting-on-a-tasks-result – nevalenny Nov 20 '16 at 19:58
  • I'm very grateful to you for the explanations! Bye – Old-fashioned-dev Nov 20 '16 at 20:31