|
Re: Threading
The timer control isn't actually 'multithreading.' The OS posts a message to the message loop on the main thread at the specified interval. Only one thread actually exists. The timer going off is entirely dependent on your main thread returning to the message loop and checking for messages. (Form/control events are raised by the message loop in response to window messages. The reason the form will 'freeze up' when you put something time consuming in an event handler is because it can't check for messages until the handler returns).
The other timer classes (such as in System.Threading) actually spawn a background thread which sleeps until it is supposed to go off. This will work regardless of if your main thread is busy, but you then have to deal with the issues associated with multiple threads.
Sometimes it makes sense to do more than one thing at once. Perhaps you have an algorithm that needs to take advantage of multiple cores/processors. Or perhaps you have a single processor system, but want to use the processor as effectively as you can. Just as one running program will take advantage of another running program sleeping, using multiple threads lets the OS scheduler give you time where you would otherwise not have any. Say you are reading and processing a large file. Reading from file is a time consuming operation. You don't know how busy the disk is or how far it has to seek. Your request might be at the end of a rather long queue. Even in the best case, we're talking milliseconds. A millisecond is a long time. With a single thread, while you're waiting on data from the hard drive, you can't process any data. And while you're processing data, you can't queue any read requests, so the disk may well spin idle. Say you have two threads, one which reads the file in some kind of logical chunks and posts the each chunk to a shared queue, and another which does processing chunk by chunk, grabbing each chunk from the shared queue. And perhaps you have a 3rd thread handling the user interface. Every 50th chunk, the processing thread posts a message to update a progress bar. But the rest of the interface code can be written as if the background operations don't even exist.
__________________
MD5(sig) = bcef75433db02e9ad9bf81d6f7c5c270
|