async
C# の new キーワードとキーワードを使用してメソッドを呼び出している多層 .Net 4.5 アプリケーションawait
がハングするだけで、その理由がわかりません。
一番下には、データベース ユーティリティを拡張する async メソッドがありますOurDBConn
(基本的には、基になるオブジェクトDBConnection
とDBCommand
オブジェクトのラッパーです)。
public static async Task<T> ExecuteAsync<T>(this OurDBConn dataSource, Func<OurDBConn, T> function)
{
string connectionString = dataSource.ConnectionString;
// Start the SQL and pass back to the caller until finished
T result = await Task.Run(
() =>
{
// Copy the SQL connection so that we don't get two commands running at the same time on the same open connection
using (var ds = new OurDBConn(connectionString))
{
return function(ds);
}
});
return result;
}
次に、これを呼び出して実行中の遅い合計を取得する中間レベルの非同期メソッドがあります。
public static async Task<ResultClass> GetTotalAsync( ... )
{
var result = await this.DBConnection.ExecuteAsync<ResultClass>(
ds => ds.Execute("select slow running data into result"));
return result;
}
最後に、同期的に実行される UI メソッド (MVC アクション) があります。
Task<ResultClass> asyncTask = midLevelClass.GetTotalAsync(...);
// do other stuff that takes a few seconds
ResultClass slowTotal = asyncTask.Result;
問題は、その最後の行に永久にハングすることです。を呼び出しても同じことを行いますasyncTask.Wait()
。遅い SQL メソッドを直接実行すると、約 4 秒かかります。
私が期待している動作は、 に到達したときにasyncTask.Result
、終了していない場合は終了するまで待機し、終了したら結果を返すことです。
デバッガーでステップスルーすると、SQL ステートメントは完了し、ラムダ関数は終了しますが、return result;
行にGetTotalAsync
は到達しません。
私が間違っていることは何か分かりますか?
これを修正するためにどこを調査する必要があるかについて何か提案はありますか?
これはどこかでデッドロックである可能性がありますか?もしそうなら、それを見つける直接的な方法はありますか?