Xamarin跨线程

Xamarin中后台线程发送到UI中操作的一个小方法:

    class Maneger : Activity    //必须继承Activity类
    {
        ...
        public delegate void DGSendMsg(string str);
        DGSendMsg dgSendMsg;
        ...

        public Maneger(DGSendMsg dgSendMsg)
        {
            this.dgSendMsg = dgSendMsg;
            ...
            thread = new Thread(ReceMsg);
            thread.IsBackground = true;
            thread.Start();
            ...
        }

        private void ReceMsg()
        {
            ...
            RunOnUiThread(() => dgSendMsg("HAHAHAHAH"));
            ...
        }
        ...
    }

原文资料:Using Background Threads in Mono For Android Applications

.NET Thread Object

One option is to explicitly spin up a new thread yourself, forcing the execution to happen off the main thread. Since we have the .NET framework to leverage, we can just use the Thread object from System.Threading like you would in any other .NET application.

private void loginWithThread()  
{
    _progressDialog.Show();

    new Thread(new ThreadStart(() =>
    {
        _loginService.Login("greg");

        RunOnUiThread(() => onSuccessfulLogin());
    })).Start();
}

Now the service processing will happen off of the UI thread, and the application can remain responsive in the meantime. One key difference you might notice is the use of RunOnUiThread(). The reason for this is that all UI updates must be made from the UI thread (you’ll be greeted by an exception if you forget to do so). Since we’re doing the login in a background thread, we use RunOnUiThread to run the updates back on the UI thread. This approach will work across MonoTouch and Windows Phone 7 as well.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我们常说,不逃课、不挂科、不恋爱、没有夜不归宿的大学生活是不完整的。 就这样无忧无虑地度过了四年时光,有一天在找工...
    有识之士阅读 4,704评论 0 1
  • 涛哥喜欢车,已经无从考究是什么时候开始喜欢上车了,只记得7岁多上小学二年级的时候就立下了长大买悍马走烂路的梦...
    涛妈很忙阅读 3,828评论 0 0
  • 之所以喜欢诗,最初应该是喜欢诗的韵律。朗朗上口,有音律的美感,这种音律上的美感便于读咏,便于记忆。从流传到现...
    天山逸云阅读 2,241评论 3 1
  • 春寒雨潇潇,落英正片片。 苍天妒英才,黄公别凡间。 铜川文苑里,再难聆哲言。 久仰先生名,无缘晤君面。 好读先生文...
    弓长宽亮阅读 2,507评论 0 1
  • Bird 哈哈哈 > 这个 1986. What a great season. model 是模型 这是一个普通...
    音吹阅读 2,688评论 0 0