Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Async on Android - an interesting lesson from competition

$
0
0

Dot42 also implemented 'async' keyword in their C# product for Android, and I tried porting to it my async test project (see http://stackoverflow.com/questions/16779793/how-to-implement-callbacks-in-c-sharp-using-async-wait-with-xamarin-for-android ). My first attempt failed with a crash somewhere in Dot42 libraries, awaiting (asynchronously, of course :) ) for a fix from them, but there is an interesting fact they observed and implemented when it comes to 'async' calls from Android activity event handlers:

By default, if there is some activity "configuration change" while you're awaiting a result of a long async operation inside an activity event handler, such as e.g. orientation change, the activity is destroyed and re-created by the system. If after such change you return from 'async' operation to the middle of an event handler code, the 'this' object of the activity is no longer valid, and if you stored some object pointing to controls within this activity, they are also invalid (they point to the old, now destroyed objects).

I hit this problem in my production code (in Java) and worked-around by configuring the activity to be notified, and not destroyed and recreated on such events. Dot42 came with another alternative, quite interesting:

var data = await webClient
                 .DownloadDataTaskAsync(myImageUrl)
                 .ConfigureAwait(this);

The .configureAwait(this) extension (plus one more code line in activity OnCreate() to setup things) ensures that your 'this' object is still valid, points to the current instance of activity, when you return from await, even if configuration change occurs. I think it's good to at least be aware of this difficulty, when you start using async/await with Android UI code, see more writeup on this at Dot42 blog: http://blog.dot42.com/2013/08/how-we-implemented-asyncawait.html?showComment=1377758029972#c6022797613553604525

Greg


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>