Asynchronous Coding Concepts for Tizen .NET Applications
asynchronous coding is essential for writing responsive and efficient programs. however, writing good asynchronous code is often not easy. some bad asynchronous code even leads to hard-to-diagnose problems like deadlocks. in this article, i'll explain a few basic concepts of asynchronous coding in c# and some common practices in tizen applications. how is asynchronous coding different from multi-threading? asynchronous coding allows a program to run multiple tasks at once without blocking a specific thread. however, this does not necessarily mean that another thread is created. for example, if a program started a task on the main thread to read some large data from the storage, the program can still do something else on that thread until the data are fully read. you may think async code seems a little like multithreaded code. after all, many methods could be executing at the same time in both. in reality, async programming can be used together with singular or multithreaded applications. this means you can have a single-threaded async program, where one thread can run concurrent tasks. conversely, you can also have a multi-threaded async application, where multiple threads can each run multiple concurrent tasks. leslie richardson - how do i think about async code?! i'll show you what really happens with this simple code: static void main() { asynccontext.run(start); } static async task start() { var task = dosomethingasync(); thread.sleep(1000); await task; thread.sleep(1000); } static async task dosomethingasync() { await task.delay(1000); } don't worry about asynccontext.run. it's used to make this console program have a ui app-like nature. this program is single-threaded, but runs two concurrent tasks at once: running an async task (dosomethingasync) for a second and doing some other computation (thread.sleep) for a second. after the task finishes, it again does some computation (thread.sleep) for a second. as shown in the below trace, the program only takes two seconds to finish and everything happens in a single thread. notice that the two thread.sleep calls have different callstacks although they have the same caller (start) in the code. this is because the compiler internally deconstructs and transforms the async method into an async state machine at compile time. (you don't have to learn the details right now.) when should i use async code? there are three major types of asynchronous operations. you have to identify which one of these fits your need. 1. i/o-bound work when you perform an i/o operation (such as sending a network request or reading a large file from disk), you don't want the whole application ui to freeze until the operation finishes. the await keyword in the following example allows the caller thread to do other work (such as handling ui events) while the network operation is in progress. there is no need to create a thread. button.clicked += async (s, e) => { var result = await httpclient.getstringasync(requesturi); label.text = result; }; note: although you don't typically need threading for i/o-bound work, you may sometimes have to use synchronous apis which do not natively support asynchronous operations (for example, datacontractserializer.writeobject). in that case, a sync api can be wrapped into an async api using a background thread (or preferably, re-implement the async api). for how to use a background thread, read the next section. 2. cpu-bound work a background thread can be used if you don't want a specific thread to be occupied by a heavy computational job for a long time. this type of concurrency is also called parallelism or multi-threading. you can generally use task.run to offload work to a background thread in most cases. consider you have a large json text that requires a noticeable amount of time to be deserialized. the following example parses a json string into an instance of book class on a thread pool thread. without task.run, you experience an uncomfortable delay when pressing the button because the operation blocks the ui thread. button.clicked += async (s, e) => { var book = await task.run(() => { return jsonserializer.deserialize<book>(jsonstring); }); label.text = book.title; }; 3. ui transitions this is the most common scenario where a developer encounters an async task for the first time when developing a ui application. in xamarin.forms, most page transitions (such as navigationpage.pushasync) and animations have a return type of task, which means that the operations are done asynchronously. similarly to the i/o-bound scenario, you can simply use the async and await keywords to wait for the task completion. button.clicked += async (s, e) => { await navigation.pushasync(page); }; notice that the await expression has no return value. you might think that you can just call navigation.pushasync without the async and await keywords (it's syntactically correct). however, not properly waiting for a task returned by an asynchronous method is not safe. i'll explain why in the next chapter. important principles badly written asynchronous code is an evil. keep the following principles in mind when you write any asynchronous code. 1. avoid async void as described in many other articles, you should always avoid using async void methods in your code. the main reason is their unique exception handling semantics. any exception thrown by the async void methods cannot be caught by their callers and always crashes the process. async/await - best practices in asynchronous programming: avoid async void by stephen cleary asynchronous programming: async void by david fowler removing async void by john thiriet there are only three exceptions when you can use async void. otherwise, all async methods should return tasks which can be awaited by their callers. app lifecycle methods (oncreate, onstart, etc.) event handlers commands (icommand implementations) caution: just changing the signature of the method from async void to async task (and not waiting for the returned task) makes the problem even worse. any exception thrown by the unawaited task is silently ignored (actually, it's captured within the task's exception property). the following code doesn't raise an exception, but is not safe. public async task dosomethingasync() { await task.delay(1000); throw new exception(); } button.clicked += (s, e) => { _ = dosomethingasync(); // discard the result }; the above pattern is also referred to as fire-and-forget. use this pattern only if you don't really care about the task's result. consider using an extension method to enable structured error logging. 2. avoid .result and .wait() it is sometimes tempting to use task.result or task.wait to synchronously wait for task completion without having to use async/await. never use them because they can lead to immediate deadlocks when used in ui applications. blocking a thread for a background task (sync-over-async) is always a bad idea. don't block on async code by stephen cleary asynchronous programming: avoid using task.result and task.wait by david fowler async/await - best practices in asynchronous programming: async all the way by stephen cleary the best solution is to use async and await. the problem usually arises when a developer wants to change only a small part of their application and 'hide' asynchronous operations from the rest of the code. however, switching from sync to async often requires significant changes in your application. for example, you may have to implement a new inotifypropertychanged-based type to visualize the progress and the result of the currently running asynchronous operation. if the callee is a pure library method which knows nothing about the app ui, you can make use of .configureawait(false) to enable synchronous calls to the method. adding .configureawait(false) to every occurrence of await in the callee method prevents deadlocks. however, this is a dangerous practice and not generally recommended. scenarios i have investigated some common patterns of using async code in tizen applications. some of them are listed below. 1. ui transitions any ui transitions including animations and page navigations (.pushasync, .popasync, .poptorootasync) should be awaited in xamarin.forms applications even though there is no extra work to do after the await expression. ❌ don't private void ondismissbuttonclicked(object s, eventargs e) { navigation.popasync(); } ✅ do private async void ondismissbuttonclicked(object s, eventargs e) { await navigation.popasync(); } 2. async commands the icommand interface is often used to define a data binding between a xaml file and a viewmodel in the mvvm architecture. similar to an event handler, a command can be constructed using an async void action delegate. make sure all exceptions are captured in the scope of the command so as not to crash your application. public icommand checkforecastcommand = new command(checkforecast); private async void checkforecast() { ... } another approach is to implement a custom asynccommand class to visualize the command's execution status using data binding. for more details, read the post async programming : patterns for asynchronous mvvm applications: commands. 3. async constructors the await keyword cannot be used in constructors because they are synchronous. i've seen many developers using async void methods for asynchronous construction without considering the exact consequences. as stated above however, this kind of code should be avoided: ❌ don't private readonly sqliteasyncconnection _database; public recorddatabase() { _database = new sqliteasyncconnection(path); initializeasync(); } private async void initializeasync() { await _database.createtableasync<record>(); } instead, the factory pattern can be used to enable async construction. the caller should await the static method createasync to instantiate this type. ✅ do private readonly sqliteasyncconnection _database; public recorddatabase() { _database = new sqliteasyncconnection(path); } private async task<recorddatabase> initializeasync() { await _database.createtableasync<record>(); return this; } public static task<recorddatabase> createasync() { var instance = new recorddatabase(); return instance.initializeasync(); } there are also other approaches. the asynclazy pattern is useful when the creation of an expensive resource can be delayed until it's actually needed. if the type is instantiated using data binding, you can implement the inotifypropertychanged interface to update the ui according to the status of the asynchronous initialization. for more details, see the post async oop 2: constructors by stephen cleary. 4. wrapping event-based apis many tizenfx apis follow the event-based asynchronous pattern (eap). you may want to wrap some of these apis into task-based asynchronous calls using taskcompletionsource to make your code more readable and easier to understand. a common example of this is asking users for privacy-related privileges using the privacyprivilegemanager api. public async task<bool> checkprivilege() { switch (privacyprivilegemanager.checkpermission(healthinfo_privilege)) { case checkresult.allow: return true; case checkresult.deny: return false; case checkresult.ask: if (!privacyprivilegemanager.getresponsecontext(healthinfo_privilege).trygettarget(out var context)) return false; var tcs = new taskcompletionsource<bool>(); context.responsefetched += (s, e) => { if (e.cause == callcause.answer) tcs.setresult(e.result == requestresult.allowforever); else tcs.setresult(false); }; privacyprivilegemanager.requestpermission(healthinfo_privilege); return await tcs.task; default: return false; } } the responsefetched event is raised when there is a user response for privacyprivilegemanager.requestpermission. the wrapper task is awaited until the result is set by the eventhandler associated with the event. you can also consider registering a cancellationtoken to set a timeout for the task. advanced tips 1. use .configureawait(false) for library code it is recommended to use .configureawait(false) for every await call in your (non-ui) library code. it prevents deadlocks when the code is accidentally called from a synchronous context in the user code. tizen has its own synchronizationcontext-derived type (tizensynchronizationcontext) just as other platforms (such as winforms and wpf) do. for more details, read the following articles. why you should use configureawait(false) in your library code by juan don't block on async code by stephen cleary configureawait faq by stephen toub 2. run ui code on the ui thread when you manipulate the app ui in your code, make sure to do it on the ui thread. otherwise, the code will not act as you expect. your code runs on the ui thread unless you explicitly use a thread (task.run) or a non-default context (.configureawait(false)). for example, in the following code, the current synchronizationcontext is captured by the await keyword, and the code after await also runs on the same context. if you change task.delay(100) to task.delay(100).configureawait(false), the context is null and changing the button text has no effect. private async void onbuttonclicked(object sender, eventargs e) { await task.delay(100); button.text = "clicked"; } the following code is incorrect because it tries to change the ui from a background (thread pool) thread. there is no synchronizationcontext for a thread pool thread. private void onbuttonclicked(object sender, eventargs e) { task.run(() => { button.text = "clicked"; }); } in a xamarin.forms application with the mvvm architecture, it is generally possible to update viewmodels from non-ui threads. however, the better practice is to use device.begininvokeonmainthread to avoid any confusion. 3. tizenfx thread-safety tizenfx apis are not generally meant to be thread-safe. if you call apis which are not marked to be thread-safe simultaneously from different threads, they may lead to incorrect results or even deadlocks. for now, i recommend calling tizenfx apis only from the main (ui) thread. conclusion although i've tried to provide as many details as possible, there are also other patterns you may face in real-world applications. if the above information is not sufficient to fit your need, you can find other materials on the web, including the pages i linked below. if you don't feel you fully understand all the concepts, simply note that you should try to complete your code first, and then polish it as you can. even though your code doesn't meet the async standards, it should generally work for most cases. asynchronous programming task-based asynchronous programming c# deadlocks in depth - part 2 by michael shpilt understanding async, avoiding deadlocks in c# by eke péter if you have any questions or feedback, please let me know at swift.kim@samsung.com.