Expected result:
TestAsync
is called by UI thread and a worker thread executes LongTask
.
Actual result:
Ui thread executes everything
Test:
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// [...]
_fab = root.FindViewById<FloatingActionButton>(...);
_fab.Click += ((sender, v) => TestAsync("fab"));
// [...]
}
private async void TestAsync(string origin)
{
await LongTask();
}
private async Task LongTask()
{
while (true) { } // Thread should hung here
}
Outcome: The Ui freezes.
Test 2: In order to make sure the UI is executing everything, I made a network operation instead (which is not allowed in the UI thread in Android)
public async Task<int> Network(string s)
{
URL url = new URL("http://www.randomtext.me/api/");
Java.IO.BufferedReader reader = new Java.IO.BufferedReader(new Java.IO.InputStreamReader(url.OpenStream()));
int count = 0;
string str;
while ((str = reader.ReadLine()) != null) {
count += str.Length;
}
reader.Close();
await Task.Delay(3000); // To make sure this method is compiled as async even though it isn't necessary
return count;
}
Outcome: NetworkOnMainThreadException
.
Question:
Why aren't LongTask
nor Network
methods executed in a worker thread ? What are await
/async
for then ?
Thanks.