首页 > 系统 > iOS > 正文

android 和 ios中实现类似C#的BackgroundWorker接口

2019-11-06 09:49:45
字体:
来源:转载
供稿:网友

移动应用为支持各种功能,大多采用了多线程技术。使用单独的线程执行某些任务,同时不影响界面的刷新,在线程执行过程中,可能需要通知一些信息给界面线程,在线程结束之后,需要告诉界面线程执行的结果,这是较为通用的一种线程执行方式。

    在C#中,实现该功能的类是BackgroundWorker,而在android和ios中,并无类似的封装好的类。通常在开发应用的时候需要考虑可移植性,存在为多种平台开发相同应用的情况,为简化不同平台应用的开发,编程需要考虑相同的逻辑结构。因此在android和ios实现与BackgroundWorker类似的功能和接口。

1.C#的BackgroundWorker

    BackgroundWorker包含的主要属性和接口说明如下:

   主要属性:

    event DoWorkEventHandler DoWork;  //线程的主体    event PRogressChangedEventHandler ProgressChanged;  //线程运行过程中的消息    event RunWorkerCompletedEventHandler RunWorkerCompleted; //线程结束时的处理

    主要函数:

    void CancelAsync();  取消线程的运行    void ReportProgress(int percentProgress, object userState);  //报告线程的消息    void RunWorkerAsync(object argument);  //开始执行线程

    为了方面使用,可以将BackgroundWorker进行封装如下

   

    public class StarBackgroundWorker    {        private BackgroundWorker m_worker;        public StarBackgroundWorker()        {            m_worker = new BackgroundWorker();        }        public void CancelAsync()        {            m_worker.CancelAsync();        }        public void RunAsync(DoWorkEventHandler DoWork, object userState, ProgressChangedEventHandler ProgressChanged, RunWorkerCompletedEventHandler RunWorkerCompleted)        {            m_worker.DoWork += DoWork;            m_worker.WorkerSupportsCancellation = true;            m_worker.RunWorkerCompleted += RunWorkerCompleted;            if (ProgressChanged != null)            {                m_worker.ProgressChanged += ProgressChanged;                m_worker.WorkerReportsProgress = true;            }            m_worker.RunWorkerAsync(userState);        }        public void ReportProgress(int percentProgress, object userState)        {            m_worker.ReportProgress(percentProgress, userState);        }    }

    使用方法:

StarCoreBackgroundWorker myworker = new StarCoreBackgroundWorker();myworker.RunAsync(    (object sender1, DoWorkEventArgs e1) =>    {        BackgroundWorker worker = sender1 as BackgroundWorker;        //线程的主体    },    null,    (object sender1, ProgressChangedEventArgs e1) =>    {        //--在界面线程中执行,可以刷新界面    },    (object sender1, RunWorkerCompletedEventArgs e1) =>    {        //--在界面线程中处理,线程运行结束后的处理    });

2.Android中实现类似BackgroundWorker的功能

Android中使用java编程,通常创建线程使用Thread和Runnable,线程与界面线程通信使用消息的方式,从界面线程中的handler获取一条消息结构,填充参数,使用sendMessage将消息发送给界面线程。界面线程的Handler获取消息队列中的消息进行处理。利用这些方式,可以实现类似c# BackgroundWorker功能

a. 封装Handler

    由于采用Handler处理所有BackgroundWorker线程中的消息,为了区分不同的线程,需要线程在创建时进行登记。代码如下:

public class StarUIHander {    static public Handler handler;    static int InvokeTag = 0;    static HashMap<Integer,HandlerCallBack> CallBackList;    public interface HandlerCallBack {        void Invoke(Message msg);    }    static int Register(HandlerCallBack CallBack)    {        int Val = InvokeTag;        CallBackList.put(InvokeTag,CallBack);        InvokeTag ++;        return Val;    }    static void Remove(int Which)    {        CallBackList.remove(Which);    }    static void InitStarUIHander()    {        handler = new android.os.Handler() {            public void handleMessage(Message msg) {                HandlerCallBack CallBack = CallBackList.get(msg.what);                if( CallBack != null )                    CallBack.Invoke(msg);            }        };        CallBackList = new HashMap<Integer,HandlerCallBack>();    }}

    在android应用主Activity中,调用InitStarUIHander初始化Handler,对于创建的线程,调用Register注册消息处理函数,获取标识,使用该标识发送消息时。

b. 实现BackgroundWorker功能

    在实现BackgroundWorker之前,参照c#的定义,需要实现一些相关的接口。有以下几个:    CancellationTokenSource, ProgressChangedEventArgs, DoWorkEventArgs,RunWorkerCompletedEventArgs,具体代码可参考附件

   

public BackgroundWorker(){    //_dispatcher = this.Dispatcher;    cts = new CancellationTokenSource();    HandlerQueue = StarUIHander.Register(new StarUIHander.HandlerCallBack() {        @Override         public void Invoke(Message msg) {            Object[] Para = (Object[])msg.obj;            switch ((int)Para[0]) {            case Message_ReportProgress:                if (ProgressChanged != null ){                    ProgressChanged.Invoke(this,(ProgressChangedEventArgs)Para[1]);                }                break;            case Message_OnRunWorkerCompleted:                if (RunWorkerCompleted != null)                    RunWorkerCompleted.Invoke(this,(RunWorkerCompletedEventArgs)Para[1]);                break;            }        }    });}

    报告状态:

public void ReportProgress(int percentProgress, Object userState){    if (ProgressChanged != null ){        Message message = StarUIHander.handler.obtainMessage();        message.what = HandlerQueue;        message.obj = new Object[]{Message_ReportProgress,new ProgressChangedEventArgs(percentProgress,userState)};        StarUIHander.handler.sendMessage(message);    }}

    创建线程执行:

public void RunWorkerAsync(Object userState){    final BackgroundWorker m_worker = this;    if (DoWork != null)    {        IsBusy = true;        try {            final DoWorkEventArgs args = new DoWorkEventArgs(userState);            new Thread(new Runnable(){                @Override                public void run() {                    DoWork.Invoke(m_worker, args);                    IsBusy = false;                    if (RunWorkerCompleted != null) {                        Message message = StarUIHander.handler.obtainMessage();                        message.what = HandlerQueue;                        message.obj = new Object[]{Message_OnRunWorkerCompleted, new RunWorkerCompletedEventArgs(args.Result, null, args.Cancel)};                        StarUIHander.handler.sendMessage(message);                    }                }            }).start();        }        catch (Exception ex) {            IsBusy = false;            if (RunWorkerCompleted != null) {                Message message = StarUIHander.handler.obtainMessage();                message.what = HandlerQueue;                message.obj = new Object[]{Message_OnRunWorkerCompleted, new RunWorkerCompletedEventArgs(false, ex, false)};                StarUIHander.handler.sendMessage(message);            }        }    }}

     为了方面使用,将BackgroundWorker进行封装如下

    public static class StarCoreBackgroundWorker    {        private BackgroundWorker m_worker;        public StarCoreBackgroundWorker()        {            m_worker = new BackgroundWorker();        }        public void CancelAsync()        {            m_worker.CancelAsync();        }        public void RunAsync(DoWorkEventHandler DoWork, Object userState, ProgressChangedEventHandler ProgressChanged, RunWorkerCompletedEventHandler RunWorkerCompleted)        {            m_worker.DoWork = DoWork;            m_worker.WorkerSupportsCancellation = true;            m_worker.RunWorkerCompleted = RunWorkerCompleted;            if (ProgressChanged != null)            {                m_worker.ProgressChanged = ProgressChanged;                m_worker.WorkerReportsProgress = true;            }            m_worker.RunWorkerAsync(userState);        }        public void ReportProgress(int percentProgress, Object userState)        {            m_worker.ReportProgress(percentProgress, userState);        }    }

    使用方法:

StarBackgroundWorker myworker = new StarBackgroundWorker();myworker.RunAsync(        new DoWorkEventHandler() {            public void Invoke(Object sender1, DoWorkEventArgs e1) {                BackgroundWorker worker = sender1 as BackgroundWorker;                //线程的主体            }        },        null,        new ProgressChangedEventHandler() {            public void Invoke(Object sender1, ProgressChangedEventArgs e1) {                //--在界面线程中执行,可以刷新界面            }        },        new RunWorkerCompletedEventHandler() {            public void Invoke(Object sender, RunWorkerCompletedEventArgs e)             {                //--在界面线程中处理,线程运行结束后的处理            }       });

3. ios中实现类似BackgroundWorker的功能

    ios创建线程可以使用NSThread,在界面线程中运行调用performSelectorOnMainThread函数;也可以使用GCD相关的函数,对多线程进行封装,可以实现类似c#的BackgroundWorker功能

a. 实现BackgroundWorker功能

    与android类似,在实现BackgroundWorker之前,参照c#的定义,同样需要实现一些相关的接口。有以下几个:CancellationTokenSource, ProgressChangedEventArgs, DoWorkEventArgs,RunWorkerCompletedEventArgs,具体代码可参考附件

    定义接口:

typedef void(^ProgressChangedEventHandler)(id,ProgressChangedEventArgs*);typedef void(^RunWorkerCompletedEventHandler)(id,RunWorkerCompletedEventArgs*);typedef void(^DoWorkEventHandler)(id,DoWorkEventArgs*);

    实现BackgroundWorker

    上报状态:

-(void)ReportProgress:(uint)percentProgress userState:(id)userState{    if (ProgressChanged != nil || ProgressChangedSelector != nil ){        dispatch_async(dispatch_get_main_queue(),^{            @try{                if( ProgressChangedSelector == nil )                    ProgressChanged(self,[ProgressChangedEventArgs initProgressChangedEventArgs:percentProgress UserState:userState]);                else{                    IMP imp = [SelectorController methodForSelector:ProgressChangedSelector];                    void (*func)(id, SEL, id, ProgressChangedEventArgs* ) = (void *)imp;                    func(SelectorController, ProgressChangedSelector, self, [ProgressChangedEventArgs initProgressChangedEventArgs:percentProgress UserState:userState]);                }            }            @catch(NSException* e)            {                            }        });    }}    异步执行

-(void)RunWorkerAsync:(id)userState{    if (DoWork != nil || DoWorkSelector != nil)    {        @try {            DoWorkEventArgs* args = [DoWorkEventArgs initDoWorkEventArgs:userState];            dispatch_async(dispatch_get_global_queue(0, 0),^{                if( DoWork != nil )                    DoWork(self,args);                else if(DoWorkSelector != nil ){                    IMP imp = [SelectorController methodForSelector:DoWorkSelector];                    void (*func)(id, SEL, id, DoWorkEventArgs* ) = (void *)imp;                    func(SelectorController, DoWorkSelector, self,args);                }                dispatch_async(dispatch_get_main_queue(),^{                    if (RunWorkerCompleted != nil)                        RunWorkerCompleted(self,[RunWorkerCompletedEventArgs initRunWorkerCompletedEventArgs:args.Result Cancelled:args.Cancel]);                    else if(RunWorkerCompletedSelector != nil){                        IMP imp = [SelectorController methodForSelector:RunWorkerCompletedSelector];                        void (*func)(id, SEL, id, RunWorkerCompletedEventArgs* ) = (void *)imp;                        func(SelectorController, RunWorkerCompletedSelector, self,[RunWorkerCompletedEventArgs initRunWorkerCompletedEventArgs:args.Result Cancelled:args.Cancel]);                    }                });            });        }        @catch(NSException* e)        {            dispatch_async(dispatch_get_main_queue(),^{                if (RunWorkerCompleted != nil)                    RunWorkerCompleted(self,[RunWorkerCompletedEventArgs initRunWorkerCompletedEventArgs:e]);                else if( RunWorkerCompletedSelector != nil ){                    IMP imp = [SelectorController methodForSelector:RunWorkerCompletedSelector];                    void (*func)(id, SEL, id, RunWorkerCompletedEventArgs* ) = (void *)imp;                    func(SelectorController, RunWorkerCompletedSelector, self,[RunWorkerCompletedEventArgs initRunWorkerCompletedEventArgs:e]);                }            });        }    }}

 

b. 为了方面使用,将BackgroundWorker进行封装如下

-(void)RunAsync:(DoWorkEventHandler)DoWork userState:(id)userState ProgressChanged:(ProgressChangedEventHandler)ProgressChanged RunWorkerCompleted:(RunWorkerCompletedEventHandler)RunWorkerCompleted{    m_worker.DoWork = DoWork;    m_worker.RunWorkerCompleted = RunWorkerCompleted;    if (ProgressChanged != nil)    {        m_worker.ProgressChanged = ProgressChanged;    }    [m_worker RunWorkerAsync:userState];}-(void)ReportProgress:(uint)percentProgress userState:(id)userState{    [m_worker ReportProgress:percentProgress userState:userState];}使用方法:

StarBackgroundWorker* myworker = [StarBackgroundWorker initStarBackgroundWorker];            [myworker RunAsync:^(id sender1, DoWorkEventArgs *e) {                BackgroundWorker* worker = (BackgroundWorker*)sender1;                            } userState:nil ProgressChanged:^(id sender1, ProgressChangedEventArgs *e) {            } RunWorkerCompleted:^(id sender1, RunWorkerCompletedEventArgs *e) {            }            }];

4. 结束语

    如果不考虑可移植性,可以直接使用android,ios,windows中定义的多线程方法开发应用,但由于不同平台采用的是不同语言,多线程实现接口和方式不同,会影响应用的逻辑结构,增加不同平台移植的工作量。基于线程执行过程,参考C#中的BackgroundWorker机制,在android和ios实现了类似的多线程机制,采用相同的框架结构,提供类似的接口,可以使多线程在不同平台具有相同的逻辑结构

    上面的代码不完整,具体请参考附件

下载附件


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表