mono touch中,Async/Await 关键词应用举例

原文:http://docs.xamarin.com/guides/ios/user_interface/controls/part_2_-_working_with_the_ui_thread/

Async/Await Example

When using the C# 5 async/await keywords InvokeOnMainThread is not required because when an awaited task completes the method continues on the calling thread.

This example code (which awaits on a Delay method call, purely for demonstration purposes) shows an async method that is called on the UI thread (it is a TouchUpInside handler). Because the containing method is called on the UI thread, UI operations like setting the text on a UILabel or showing a UIAlertView can be safely called after asynchronous operations have completed on background threads.

async partial void button2_TouchUpInside (UIButton sender)
{
    textfield1.ResignFirstResponder ();
    textfield2.ResignFirstResponder ();
    textview1.ResignFirstResponder ();
    label1.Text = "async method started";
    await Task.Delay(1000); // example purpose only
    label1.Text = "1 second passed";
    await Task.Delay(2000);
    label1.Text = "2 more seconds passed";
    await Task.Delay(1000);
    new UIAlertView("Async method complete", "This method", 
               null, "Cancel", null)
        .Show();
    label1.Text = "async method completed";
}

If an async method is called from a background thread (not the main UI thread) then InvokeOnMainThreadwould still be required.

具体应用可参考: http://blog.csdn.net/joyhen/article/details/17006101


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值