AsyncCallback for a thread on compact framework

2019-04-12 04:43发布

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条回答
对你真心纯属浪费
2楼-- · 2019-04-12 05:12

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-04-12 05:15

I know this is an old question, but if you are using CF 3.5 this would be a nice an short solution to the problem. Using lambda delegate..

ThreadStart starter = () => DoWorkMethodWithParams( param1, param2);
Thread myNewThread = new Thread(starter){IsBackground = true};
myNewThread.Start();
查看更多
登录 后发表回答