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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值