John L.
John L.

Reputation: 1953

Thread Yielding Before Async-Await

Before the introduction of async-await programming into C#, how was one able to put a network request into another thread and yield execution time back to the CPU until a response is received so that this thread will not waste CPU time?

Because when CPU allocates time to this thread and thread sits idle waiting for a response, that would be a waste of CPU time, right?

Upvotes: 1

Views: 97

Answers (1)

TheGeneral
TheGeneral

Reputation: 81543

In several ways, however Asynchronous Programming Model (APM) was the go-to for this type of Asynchrony

An asynchronous operation that uses the IAsyncResult design pattern is implemented as two methods named BeginOperationName and EndOperationName that begin and end the Asynchronous Operation OperationName respectively. For example, the FileStream class provides the BeginRead and EndRead methods to Asynchronously read bytes from a file. These methods implement the asynchronous version of the Read method.

To answer your question

Because when CPU allocates time to this thread and thread sits idle waiting for a response, that would be a waste of CPU time, right?

No blocking a thread and waiting for a completion port to call back doesn't cause CPU cycles to run away, however polling on a thread will.

There is a lot to how this works, however an example use can be seen here

Example of usage

private static void TestWrite()
{ 
   // Must specify FileOptions.Asynchronous otherwise the BeginXxx/EndXxx methods are
   // handled synchronously.
   FileStream fs = new FileStream(Program.FilePath, FileMode.OpenOrCreate,
      FileAccess.Write, FileShare.None, 8, FileOptions.Asynchronous);

   string content = "A quick brown fox jumps over the lazy dog";
   byte[] data = Encoding.Unicode.GetBytes(content);

   // Begins to write content to the file stream.
   Console.WriteLine("Begin to write");
   fs.BeginWrite(data, 0, data.Length, Program.OnWriteCompleted, fs);
   Console.WriteLine("Write queued");
}

private static void OnWriteCompleted(IAsyncResult asyncResult)
{ 
   // End the async operation.
   FileStream fs = (FileStream)asyncResult.AsyncState;
   fs.EndWrite(asyncResult);

   // Close the file stream.
   fs.Close();
   Console.WriteLine("Write completed");

   // Test async read bytes from the file stream.
   Program.TestRead();
}

Upvotes: 2

Related Questions