views:

533

answers:

1

I need to implement threading to improve load time in a compact framework app. I want to fire off a background thread to do some calls to an external API, while the main thread caches some forms. When the background thread is done, I need to fire off two more threads to populate a data cache.

I need the background thread to be able to execute a callback method so I know it's done and the next two threads can be started, but the BeginInvoke method on a delegate is not supported in the compact framework, so how else can I do this?

+2  A: 

You can arrange it yourself, simply make sure your thread method calls a completed method (or event) when it's done.

Since CF doesn't support the ParameterizedThreadStart either, I once made a little helper class.

The following is an extract and was not re-tested:

//untested
public abstract class BgHelper
{
    public System.Exception Error { get; private set; }
    public System.Object State { get; private set; }

    public void RunMe(object state)
    {
        this.State = state;
        this.Error = null;

        ThreadStart starter = new ThreadStart(Run);
        Thread t = new Thread(starter);
        t.Start();            
    }

    private void Run()
    {
        try
        {
            DoWork();                
        }
        catch (Exception ex)
        {
            Error = ex;
        }
        Completed(); // should check Error first
    }

    protected abstract void DoWork() ;

    protected abstract void Completed();
}

You are required to inherit and implement DoWork and Completed. It would probably make sense to use a < T> for the State property, just noticed that.

Henk Holterman
Is that ok to do? I'm no threading expert but I had concerns about spawning new threads from a thread, which is what would happen here surely?
Charlie
Yes, but there is nothing special about starting a Thread form a Thread. Your main Thread is a Thread too.
Henk Holterman