c# - async/await bad practice under Android? -
currently porting existing c# windows 8 / ios app android (with xamarin).
i used lot of async/await file io, dialogs, network, etc…
what happens when app paused/suspended during await call? under windows , ios there 2 possibilities:
- the app resumed later, if nothing had happened
- the app terminated if memory low.
in both cases, there no memoy leak, there no changes in control flow.
however, under android, activity can destroyed , recreated while process stays alive. in understanding of async/await means:
- an unclosed dialog wait forever, meaning objects accessible caller ("this", local variables etc.) stay in memory forever (memory leak)
- when awaited network request finishes while former activity has been destroyed android, code after "await" (e.g. file write) collide because 2 running instances of activity exist.
are assumtions true? if yes, can done? (without making program complicated before of invention of async/await)
an android activity guaranteed call onpause before activity deactivated/destroyed , onresume when starts (see http://developer.android.com/training/basics/activity-lifecycle/index.html).
how if had cancellationtokensource available activity. in onpause can call cancel , use:
try { // async code ... } catch (operationcancelledexception e) { }
see http://msdn.microsoft.com/en-us/library/jj155759.aspx cancelling async tasks.
more suggestion definitive answer, hope helps.
edit:
when started introducing async/await code found zombie virus. once start asyncing find spreads throughout rest of code. may you've got lots of async calls same reason. there 2 rules follow:
- declare methods
public async task foo()
instead ofpublic async void foo()
- don't block on async code
in own practice, i've discovered 2 places can break these general rules.
- if you're @ 'top' (i.e. ui) of code, there may places have declare code async void because delegate you're overriding takes void return type. typical example of button.click method.
- i had database call looked single value in database. if converted async, lots of code elsewhere have change. discovered if you're guaranteed, , mean guaranteed, @ 'bottom' of code, none of methods below 1 you're calling use async, can safely call .result on task. saved me asyncing half code unnecessarily.
hope helps.
Comments
Post a Comment