Why is AwakeFromNib getting called repeatedly when using storyboards?

1.2k views Asked by At

I have a storyboard application. When the first view is loaded on startup, I have this code to instantiate my main background thread and it all works fine.

    public override void AwakeFromNib()
    {
        base.AwakeFromNib();
        // Perform one-time initialization in this function

        // Create and start the main worker thread
        MainBackgroundThread = new Thread(new ThreadStart(MainLoop.RunWorker));
        MainBackgroundThread.Start();
    }

However, when the user goes to a different view and then goes back to the first view via a segue, AwakeFromNib() is called again. I thought it was only supposed to be called once... Where do I start my main background thread so it only ever gets started once?

1

There are 1 answers

0
heckman On BEST ANSWER

AwakeFromNib will be called every time that a new instance of that view is loaded from the storyboard/segue. If you are segueing in your storyboard, you should expect AwakeFromNib to be called every time because you are truly creating a new instance of the view, from a nib object. If you want to start a background thread, you could try something like:

public override void AwakeFromNib()
{
    static NSThread * thread;

    base.AwakeFromNib();
    // Perform one-time initialization in this function

    // Create and start the main worker thread
    if(!thread)
    { 
         thread = new Thread(new ThreadStart(MainLoop.RunWorker));
    }

    MainBackgroundThread = thread;
    MainBackgroundThread.Start();
}