AsyncCallback for a thread on compact framework

血红的双手。 提交于 2019-12-06 06:59:55

问题


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?


回答1:


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.




回答2:


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();


来源:https://stackoverflow.com/questions/1063189/asynccallback-for-a-thread-on-compact-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!