非同期処理
スレッド
スレッドプール
- プロセス内全てのAppDomainで共有
- ThreadPool.QueueUserWorkItemでスレッドプールのキューに処理を送る
- デリゲートBeginInvoke内部で使用
- System.Threading.Timerのコールバックメソッドで使用
- System.Windows.Forms.Timerとは別(こちらは一つのスレッドで実行される)
非同期処理
- デリゲートBeginInvoke
- 終了待機の方法
- 完了まで待つ(EndInvoke)
- ポーリング(IAsyncResult#AsyncState)
- コールバック(AsyncCallbackデリゲート)
例外
- EndInvokeメソッドが例外をスローする。
delegate void ThrowExceptionDelegate(); static void Main(string[] args) { ThrowExceptionDelegate ted = new ThrowExceptionDelegate(ThrowException); Console.WriteLine("BeginInvoke"); IAsyncResult ar = ted.BeginInvoke(null, null); try { Console.WriteLine("EndInvoke"); ted.EndInvoke(ar); Console.WriteLine("EndInvoke called"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } static void ThrowException() { throw new Exception("test"); }
実行結果。
BeginInvoke EndInvoke test