前田稔(Maeda Minoru)の超初心者のプログラム入門
![]()
![]()
//★ 非同期で Delegate を呼び出す
using System;
using System.Threading;
// デリゲートの定義
public delegate void ShowMessage(int n);
public class DelegateTest
{
public static void Main()
{
const int N = 6;
ShowMessage asyncCall = new ShowMessage(AsynchronousMethod);
// asyncCall を非同期で呼び出す。
IAsyncResult ar = asyncCall.BeginInvoke(N, null, null);
// ↓この部分は asyncCall によって呼び出されるメソッドと同時に実行されます。
for(int i=0; i<N; ++i)
{
Thread.Sleep(600);
Console.Write("Main ({0})\n", i);
}
// asyncCall の処理が終わるのを待つ。
asyncCall.EndInvoke(ar);
Console.Write(" 処理完了\n");
Console.ReadLine();
}
// デリゲートから呼び出される static メソッド
static void AsynchronousMethod(int n)
{
for(int i=0; i<n; ++i)
{
Thread.Sleep(1000);
Console.Write("AsynchronousMethod ({0})\n", i);
}
}
}
|
![]()