Skip to content

Instantly share code, notes, and snippets.

@amay077
Created March 18, 2013 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amay077/5186620 to your computer and use it in GitHub Desktop.
Save amay077/5186620 to your computer and use it in GitHub Desktop.
Xamarin の Alpha版で async/await を試す ref: http://qiita.com/items/aa915181ab705374e00f
// ボタンが押されたよ
private async void button1_Click(Object sender, EventArgs e)
{
button.Enabled = false; // 実行中はボタン使えなくする
// 超時間のかかる計算
var result = await HeavyCalcAsync();
// ここから下は UIスレッド で実行される
button.Text = String.Format("result:{0}", result); // 結果を表示する
button.Enabled = true;
}
// 超時間のかかる計算
private static int HeavyCalc()
{
System.Threading.Thread.Sleep(10000);
return 5; // 超時間をかけて 5 を計算したつもり
}
// HeavyCalc をラップして非同期で実行
private Task<int> HeavyCalcAsync()
{
return Task.Run(() => HeavyCalc());
}
// ボタンが押されたよ
private async void button1_Click(Object sender, EventArgs e)
{
var asyncTask = new HeavyCalcTask(button);
asyncTask.Execute();
}
// HeavyCalc を非同期で実行する AsyncTask
class HeavyCalcTask : Android.OS.AsyncTask
{
private readonly Button button;
public HeavyCalcTask(Button button)
{
this.button = button;
}
#region implemented abstract members of AsyncTask
protected override void OnPreExecute()
{
button.Enabled = false; // 実行中はボタン使えなくする
}
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
{
// 超時間のかかる計算
return HeavyCalc();
}
protected override void OnPostExecute(Java.Lang.Object result)
{
button.Text = String.Format("result:{0}", result); // 結果を表示する
button.Enabled = true;
}
#endregion
}
// ボタンが押されたよ
private void button1_Click(Object sender, EventArgs e)
{
button.Enabled = false; // 実行中はボタン使えなくする
// 超時間のかかる計算
var result = HeavyCalc();
button.Text = String.Format("result:{0}", result); // 結果を表示する
button.Enabled = true;
}
// 超時間のかかる計算
private static int HeavyCalc()
{
System.Threading.Thread.Sleep(10000);
return 5; // 超時間をかけて 5 を計算したつもり
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment