I’ve ported an app from Android to Windows Phone 7, and was able to use synchronous calls to file io and the like without many problems (I use threads, so this simplifies things).
However, now I’m porting to a Windows 8 Store app, and the XxxAsync() methods are rampant in the api.
Should I just blindly use async apis and hope for the best?
I have various doubts… for example:
Say the user taps the Save button to save the data model. All the saving is done asynchronously. This means the user can go off changing the data model while it is being saved. Won’t this mess up the data and corrupt his file if it is modified midway through?
How does this make it easier for the developer?
I’ve read various async articles (such as this) but I feel as though I may be missing something…
Thanks for your insight.
The idea with async in a UI is that all your code runs on one thread (the UI thread). When the user clicks the Save button, your handler runs. At this point, the UI is busy running your code, so the UI is not interactive. When you have prepared a snapshot of the data you want to send to the server, you launch an asynchronous save and (technically speaking) your handler is finished. Control passes back to the UI, which becomes responsive again.
At this point, the user can update the data model, but the OS is not looking at the data model. It’s just making sure that a separate buffer of data (the snapshot you created in your Save button handler) is sent to the server. When that has happened, your asynchronous callback is executed – again, on the UI thread. Depending on the version you’re using, you may need to transfer that call to the UI thread manually, using BeginInvoke.
This is exactly the same model as used in JavaScript inside the browser.
It doesn’t completely solve all synchronisation problems. For example, unless you disable the Save button during the upload, the user can click save again while the server is already receiving the first save. But this is only a problem for the server to worry about, and it better be able to cope with two simultaneous attempted saves.
One possible problem you may have is with your previous versions of the application. If you were using threads all over the place, were you using locks or thread-safe data structures appropriately? The problem you describe definitely exists in a free-threaded application!