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

来源:互联网 发布:广告铃声制作软件 编辑:程序博客网 时间:2024/06/01 23:51

原文: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


0 0