- Asynchronous Programming Model allows us increase performance of our application by running certain piece of code onto a seperate thread while the main thread is blocked for some reason.
- .NET supports APM by supplying BeginXXX and EndXXX methods built-in to various library classes. (e.g. BeginRead( ) and EndRead( ) methods in Stream class)
- Rendezvous Models allow for three styles of using APM, Wait-Until-Done, Polling and Callback.
- Use null while calling an APM supportive method for Callback and state arguments to use Wait-Until-Done. If we use this, EndXXX will block current thread until Asynchronous call is completed.
- The Completed property of the IAsyncResult object returned by the BeginXXX method may be used to check (poll) whether the Asynchronous work has been completed. If not, we may keep on working on current thread.
- If BeginXXX is called by one method and EndXXX needs to be called by another method, we would need Callback Model.
- Callback model allows us to specify a method (using AsyncCallback delegate) in the BeginXXX method. This method would be called in order to complete the Asynchronous call (EndXXX).
- We may optionally supply an object (as a state object) that might be needed to call EndXXX. (Refer to page 417)
- If an Exception occurs during Asynchronous method calls, it is thrown when EndXXX is called. Reason: Since it occurred on the other thread, we cannot catch it on the main thread.
- However, in Windows Forms Applications, the Application object is notified whenever an exception occurs (either on main thread and worker threads). Therefore, we can attach a method to Application.ThreadException to handle an exceptional situation.
- Creating threads on our own is not recommended. Instead use ThreadPool class to create/reuse threads for our methods. (Don't buy threads, lease 'em)
- ThreadPool has a number of available slots to be used as threads. These slots are maintained by ThreadPool class and it keeps processor busy by continuously assigning to it slots that have pending work in them. These reusable slots may be called pre-built threads.
- We make a request to acquire a slot (whenever one becomes available) by calling ThreadPool.QueueUserWorkItem( ) static method and pass it a WaitCallback delegate representing the name of the method we wish to run as thread.
- If the Application uses a large number of Threads through ThreadPool, Threads may start to starve. In such a situation we may set the SetMaxThreads property of ThreadPool class to incease number of pre-built threads (slots).
- If faster Startup time is required, we may set the minimum number of threads in ThreadPool using SetMinThreads property.
- Typically ThreadPool class limits minimum number of threads in the pool to be 2 per second.
Wednesday, July 15, 2009
Chapter 7-Lesson 3
Labels:
APM,
Asynchronous,
Blocked,
Polling,
Rendezvous,
Starvation,
ThreadPool
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment