私はスレッド化を学んでいます.私の意図は、計算のためにいくつかの値をメソッドに渡すことです,結果が20ミリ秒以内に返されない場合,私は「操作タイムアウト」を報告します.私の理解に基づいて、私は次のようにコードを実装しました:
public delegate long CalcHandler(int a, int b, int c);
public static void ReportTimeout()
{
CalcHandler doCalculation = Calculate;
IAsyncResult asyncResult =
doCalculation.BeginInvoke(10,20,30, null, null);
if (!asyncResult.AsyncWaitHandle.WaitOne(20, false))
{
Console.WriteLine("..Operation Timeout...");
}
else
{
// Obtain the completion data for the asynchronous method.
long val;
try
{
val= doCalculation.EndInvoke(asyncResult);
Console.WriteLine("Calculated Value={0}", val);
}
catch
{
// Catch the exception
}
}
}
public static long Calculate(int a,int b,int c)
{
int m;
//for testing timeout,sleep is introduced here.
Thread.Sleep(200);
m = a * b * c;
return m;
}
質問:
(1) timeout を報告する適切な方法ですか?
(2) 時間切れの場合は EndInvoke() を呼び出しません。そのような場合、EndInvoke() の呼び出しは必須ですか?
(3) 私はそれを聞いた
「非同期メソッドの戻り値を処理したくない場合でも、EndInvoke を呼び出す必要があります。そうしないと、BeginInvoke を使用して非同期呼び出しを開始するたびにメモリ リークが発生する危険があります」
メモリに関連するリスクは何ですか? 例を挙げることができますか?