- VS2013
で、async/awaitを使ってみたのですが、例外のキャッチが上手く行かなかったのでいろいろ試してみました。
// Button1 Click Event
private async void Button1_Click(object sender, RoutedEventArgs e)
{
this.Button1.IsEnabled = false;
try
{
for (int i = 0; i < 10; i++)
{
this.TextBox1.AppendText(i + "\n");
#if true
// 非同期になるし、例外キャッチできる
await Task.Run(async () => HeavyProcess(i));
// コンパイラ警告が気になる場合は適当なawaitを追加
//await Task.Run(async () => {HeavyProcess(i); await Task.Yield();});
#else
// 非同期になるが、例外キャッチできない
await Task.Run(() => HeavyProcess(i));
#endif
}
}
catch (Exception ex)
{
this.TextBox1.AppendText(ex.Message);
}
this.Button1.IsEnabled = true;
}
// Heavy Process
void HeavyProcess(int count)
{
System.Threading.Thread.Sleep(1000);
if (count >= 5) throw new ApplicationException("例外発生!!");
}
非同期タスクをちゃんとasyncにしないとダメらしい。
正直よくわかってないので、間違いの指摘お願いします。
(2017-07-27 追記)
これはデバッグモード特有の挙動で、asyncにしなくても問題ないようです。
http://qiita.com/habu1010/items/08177698fa3826474c0b
VS2017だとデバッグでもちゃんと例外取得できてますね。
0 件のコメント:
コメントを投稿