Xamarinクロススレッド

1767 ワード

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.