Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 22 INTRODUCTION TO ASYNCHRONOUS PROGRAMMING

Asynchronous Programming Patterns

In Chapter 15, we covered the topic of delegates, and you saw that when a delegate object is invoked, it invokes the methods contained in its invocation list. This is done synchronously, just as if the methods had been called by the program.

If a delegate object has only a single method (which I’ll call the referenced method) in its invocation list, it can execute that method asynchronously. The delegate class has two methods, called BeginInvoke and EndInvoke, that are used to do this. You use these methods in the following way:

When you call the delegate’s BeginInvoke method, it starts its referenced method executing on a separate thread from the thread pool and then returns immediately to the initial thread. The initial thread then continues on while the referenced method executes in parallel.

When your program wants to retrieve the results of the completed asynchronous method, it either checks the IsCompleted property of the IAsyncResult returned by BeginInvoke or calls the delegate’s EndInvoke method to wait for the delegate to finish.

Figure 22-5 shows the three standard patterns for using this process. In all three patterns, the initial thread initiates an asynchronous method call and then does some additional processing. The patterns differ, however, in the ways in which the initial thread receives the information that the spawned thread has completed.

In the wait-until-done pattern, after spawning the asynchronous method and doing some additional processing, the initial thread halts and waits for the spawned thread to finish before continuing.

In the polling pattern, the initial thread checks periodically whether the spawned thread has completed, and if not, it continues additional processing.

In the callback pattern, the initial thread continues execution without waiting or checking whether the spawned thread has completed. Instead, when the referenced method in the spawned thread finishes, it calls a callback method, which handles the results of the asynchronous method before calling EndInvoke.

Figure 22-5. The standard patterns for asynchronous method calls

613

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]