dommer
dommer

Reputation: 19820

How do I clean up threads in MonoTouch?

Looking at the Time Profiler instrument in Instruments, it looks like I'm not disposing of threads after I've used them. The list of "All threads" grows as I do operations that start a thread.

I start my thread as follows ("thread" is local to the function):

UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;

Thread thread = new Thread(Dispatch);
thread.Start();

The Dispatch() function is:

private void Dispatch()
{
    using (NSAutoreleasePool autoreleasePool = new NSAutoreleasePool())
    {
        try
        {
            // Calls a web service.
            _workDispatcher.Dispatch();
        }
        finally
        {
            // Resets network activity indicator after thread complete.
            InvokeOnMainThread(() => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; });
        }
    }
}

_workerDispatcher.Dispatch makes a call to a web service.

What more should I be doing to destroy the thread on completion?

The application crashes after an extended period of time - and we're guessing it might be threads - as it launches them regularly to conduct shortish operations. I've read that monitoring memory usage in MonoTouch is a challenge due to garbage collection - or I'd see if memory was also being consumed (e.g. by threads remaining).

I'm using MonoTouch 3.2.5 and iOS 4.3.1 (and Instruments in Xcode 4). App needs to work on iOS 3.x, so I can't use Grand Central Dispatch.

Upvotes: 1

Views: 949

Answers (3)

dommer
dommer

Reputation: 19820

It looks like this was a garbage collection issue. If I put a call to GC.Collect() after the thread completes, the number of threads doesn't appear to keep growing.

Upvotes: 1

miguel.de.icaza
miguel.de.icaza

Reputation: 32694

MonoTouch uses two kinds of threads: the ones that you manually launch with Thread.Start and the ones that are created on demand in response to asynchronous methods invocations (internally many synchronous operations are merely wrappers around the asynchronous ones) or created when you use ThreadPool.QueueUserWorkItem or when you use the Parallel Framework's default Task scheduler.

What you might be seeing are the ThreadPool threads which are automatically configured to be N per CPU (I do not remember the actual number, but you can find out through a property in the ThreadPool).

When you run on the device you have a single core, so the threads are capped at N. When you run on an iPad 2 the threads are capped at 2*N, when you are running on a fancy iMac with 8 cores that number is 8*N. This is just Mono's way of adjusting itself to more CPUs.

Upvotes: 2

Geoff Norton
Geoff Norton

Reputation: 5056

Are you certain these are your threads? Its far more likely that MonoTouch is keeping some threadpool threads around for future async operations (like the one in the call to your web service).

Upvotes: 2

Related Questions