iOS for C# Developer - part 3: multithreading
This post is part of the series: iOS for C# Developer. Previous parts:
The most typical scenario to use multithreading is to maintain responsive UI when we do some resource-consuming computation.
C#
Let's consider simple button click action in C#:
Method Compute()
is a CPU-intensive operation (simulated by Sleep()
function).
Above code will block UI during computation. To keep UI responsive, computation has to take place in a separate thread. It can be done easily using async
/await
keywords:
iOS
This is equivalent (single-threaded) button click handler in iOS:
Multithreaded version is a little bit different. In Objective-C, there is no syntax similar to async
/await
. Thus, status update has to be invoked by background thread explicitly. Additionally, every UI operation (in this case: label text update) has to be done in the main thread. Below code, use Dispatch Queues, which is the easiest and recommended way for multithreading scenarios:
This multithreaded code will look pretty similar in Swift.
Summary
Invoking background threads is much easier from developer perspective in C#. Code is concise and more readable. Multithreading in Objective-C introduce some overhead, but it is not very hard to handle.