デリゲートの非同期呼び出し
デリゲートを定義すると、自動的に BeginInvoke と EndInvoke というメソッドが定義される。
System.IAsyncResult Delegate::BeginInvoke (orgparams, System.AsyncCallback callback, object @object); orgtype Delegate::EndInvake (System.IAsyncResult result);これらを呼び出すことによって、非同期の呼び出しを実現できる。
class MessageBox { // デリゲートを宣言 delegate System.Windows.Forms.DialogResult MessageBoxDelegate (string text, string caption, System.Windows.Forms.MessageBoxButtons buttons, System.Windows.Forms.MessageBoxIcon icon); // メッセージボックスを表示するメソッド System.Windows.Forms.DialogResult Show (string text, string caption, System.Windows.Forms.MessageBoxButtons buttons, System.Windows.Forms.MessageBoxIcon icon) { return System.Windows.Forms.MessageBox.Show (text, caption, buttons, icon); } static void Main () { MessageBox msgBox = new MessageBox (); // デリゲート作成 MessageBoxDelegate msgBoxDelegate = new MessageBoxDelegate (msgBox.Show); // 非同期に呼び出す System.IAsyncResult asyncResult = msgBoxDelegate.BeginInvoke ("ボタンが押されるのを待機します。", "待機中", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, null, null); // 終了まち while (!asyncResult.IsCompleted) { System.Threading.Thread.Sleep (1000); System.Console.WriteLine ("マダー?"); } // 戻り値を取得 System.Windows.Forms.DialogResult result = msgBoxDelegate.EndInvoke (asyncResult); } }
トラックバック
- このエントリーにトラックバック:
- http://frog.raindrop.jp/cgi-bin/mt/mt-tb.cgi/2138
コメント