Book Image

C# Multithreaded and Parallel Programming

By : Rodney Ringler
Book Image

C# Multithreaded and Parallel Programming

By: Rodney Ringler

Overview of this book

<p>Most modern machines have dual-core processors. This means that the present-day computer has the ability to multitask. Using multiple cores means your applications can process data faster and be more responsive to users. However, to fully exploit this in your applications, you need to write multithreading code.</p> <p>We will begin by covering some techniques that have been around since the beginning of .NET, including the BackgroundWorker component, timers, and the Thread class. We will use tasks, task factories, and parallel loops to develop multithreaded applications at a higher level than directly creating and managing individual threads. Finally, we will look at the tools Visual Studio provides for debugging parallel applications, common concurrent design patterns, and the latest updates in PLINQ and async.</p>
Table of Contents (18 chapters)
C# Multithreaded and Parallel Programming
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using an AsyncCallback delegate method


We have seen how we can use the APM design pattern that is implemented in the FileStream class to perform an asynchronous read and then wait on the results. We also mentioned how we can poll to see if the asynchronous read has completed instead of blocking the main thread. Now, we will see how we can execute a delegate method when the asynchronous read has completed.

Using this method, we do not have to block the main thread waiting or perform the work of polling the IsCompleted property to see when the read has completed. We simply execute the BeginRead method and pass it a delegate method. We then go on our way and, when the read completes, the delegate method will be executed.

Let's look at the method header for the BeginRead method of the FileStream class. The following is the method definition:

public override IAsyncResult BeginRead(
   byte[] array,
   int offset,
   int numBytes,
   AsyncCallback userCallback,
   Object stateObject
)

You will see...