iOS for C# Developer - part 3: multithreading

 Date: September 12, 2014

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#:

private void Button_Click(object sender, RoutedEventArgs e)
{
    this.status.Content = "Computing...";
    Compute();
    this.status.Content = "Done";
}

private void Compute()
{
    Thread.Sleep(5000);            
}

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:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    this.status.Content = "Computing...";
    await Compute();
    this.status.Content = "Done";
}

private async Task Compute()
{
    await Task.Factory.StartNew(() =>
    {
        Thread.Sleep(5000);
    });
}

iOS

This is equivalent (single-threaded) button click handler in iOS:

- (IBAction)buttonClick:(id)sender
{
    self.status.text = @"Computing...";
    [self compute];
    self.status.text = @"Done";
}

- (void)compute
{
    [NSThread sleepForTimeInterval:5];
}

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:

- (IBAction)buttonClick:(id)sender
{
    self.status.text = @"Computing...";
    [self compute];
}

- (void)compute
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        [NSThread sleepForTimeInterval:5];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.status.text = @"Done";
        });
    });
}

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.

 Tags:  programming

Previous
⏪ iOS for C# Developer - part 2: strings

Next
iOS for C# Developer - part 4: Xcode ⏩